java如何另开一个线程去播放其他音效_求教Java程序的背景音乐和操作音效怎么同时播放?...

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来播放背景音乐为什么还是不能同时播放?

展开

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值