gpt4 book ai didi

java - Java Clip 类中的 Drain 方法

转载 作者:搜寻专家 更新时间:2023-11-01 00:55:22 25 4
gpt4 key购买 nike

我正在创建一个短片然后播放它,调用 start() 方法。然后我调用 drain() 方法来阻止执行,直到剪辑播放完成。但是,多次运行下面的代码时,有时有效,有时无效,并且声音在结束前随机停止。

Mixer mixer = AudioSystem.getMixer(null);
AudioFormat format = new AudioFormat(44100, 8, 1, true, false);
DataLine.Info info = new DataLine.Info(Clip.class, format);
try {
// Create a sound of 1 second
Clip clip = (Clip)mixer.getLine(info);
byte[] b = new byte[44100];
for(int i=0; i<b.length; i++)
b[i] = (byte) (50*Math.sin(i/10.0));

clip.open(format, b, 0, b.length);
clip.setFramePosition(0);
clip.start();
clip.drain();
} catch(LineUnavailableException lue) { lue.printStackTrace(); }

所以我的问题是:这是一个错误吗?还是我误解了 drain() 方法?

最佳答案

似乎 clip.start() 有时会在错误(?)发生 Start 事件之前立即返回,在这种情况下,drain 无效。通过解决方法,我们可以使用 Listener 来捕获 START 事件:

解决方案:

Mixer mixer = AudioSystem.getMixer(null);
AudioFormat format = new AudioFormat(44100, 8, 1, true, false);
DataLine.Info info = new DataLine.Info(Clip.class, format);
try {
// Create a sound of 1 second
Clip clip = (Clip)mixer.getLine(info);

//Workaround part 1
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == Type.START)
synchronized (clip) {
clip.notify();
}
}
});

byte[] b = new byte[44100];
for(int i=0; i<b.length; i++)
b[i] = (byte) (50*Math.sin(i/10.0));

clip.open(format, b, 0, b.length);
clip.setFramePosition(0);

//Workaround part 2
synchronized (clip) {
clip.start();
clip.wait();
System.out.println("Started");
}
clip.drain();
System.out.println("Drained");
} catch(LineUnavailableException | InterruptedException lue) { lue.printStackTrace(); }

关于java - Java Clip 类中的 Drain 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34389991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com