博客分类: swing
java音乐播放器
学习过java语言的你,或多或少,在某天突发奇想,想着用swing做一个音乐播放器。但是,发现很难找到,相关的java代码,或者你下载的代码有问题,或者你代码里面引入的类包找不到。为了解决自如此类的问题。在这儿,有如下的代码可以供大家参考。
Java代码
package TheMusic;
import java.io.*;
import javax.sound.sampled.*;
public class Music {
public static void main(String[] args) {
// TODO Auto-generated method stub
//修改你的音乐文件路径就OK了
AePlayWave apw=new AePlayWave("突然好想你.wav");
apw.start();
}
}
在程序中实例化这个类,启动线程,实例化的时候参照Test修改路径就OK播放声音的类
Java代码
public class AePlayWave extends Thread {
private String filename;
public AePlayWave(String wavfile) {
filename = wavfile;
}
public void run() {
File soundFile = new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (Exception e) {
e.printStackTrace();
return;
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[512];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
好了,到此结束。