booleanisStop=true;//控制播放线程booleanhasStop=true;//播放线程状态AudioInputStreamaudioInputStream;//文件流SourceDataLinesourceDataLine;//输出设备AudioFormataudioFormat;...
boolean isStop = true;// 控制播放线程
boolean hasStop = true;// 播放线程状态
AudioInputStream audioInputStream;// 文件流
SourceDataLine sourceDataLine;// 输出设备
AudioFormat audioFormat;// 文件格式
private void play(int snum) {
//do{
try {
isStop = true;// 停止播放线程
// 等待播放线程停止
while (!hasStop) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
File file = new File( "src/sound/"+snum+".wav");
// 取得文件输入流
audioInputStream = AudioSystem.getAudioInputStream(file);
audioFormat = audioInputStream.getFormat();
// 打开输出设备
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
// 创建独立线程进行播放
isStop = false;
Thread playThread = new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
e.printStackTrace();
}
//}while(isPass());
}
private boolean isPass() {
// TODO 自动生成的方法存根
return false;
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[320];
public void run() {
try {
int cnt;
hasStop = false;
// 读取数据到缓存数据
while ((cnt = audioInputStream.read(tempBuffer, 0,
tempBuffer.length)) != -1) {
if (isStop)
break;
if (cnt > 0) {
// 写入缓存数据
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
// Block等待临时数据被输出为空
sourceDataLine.drain();
sourceDataLine.close();
hasStop = true;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
这些是播放音效的代码。我再建一个play1和playthread1来播放背景音乐为什么还是不能同时播放?
展开