我如何等待java声音片段完成播放? [英] how can I wait for a java sound clip to finish playing back?
问题描述
我使用以下代码使用java声音API播放声音文件。
I am using the following code to play a sound file using the java sound API.
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream);
clip.open(inputStream);
clip.start();
对Clip.start()方法的方法调用立即返回,系统播放声音文件在后台线程中。我希望我的方法暂停,直到播放完成。
The method call to the Clip.start() method returns immediately, and the system playbacks the sound file in a background thread. I want my method to pause until the playback has completed.
有什么好办法吗?
编辑:对于对我的最终解决方案感兴趣的每个人,根据Uri的答案,我使用下面的代码:
For everyone interested in my final solution, based on the answer from Uri, I used the code below:
private final BlockingQueue<URL> queue = new ArrayBlockingQueue<URL>(1);
public void playSoundStream(InputStream stream) {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream);
clip.open(inputStream);
clip.start();
LineListener listener = new LineListener() {
public void update(LineEvent event) {
if (event.getType() != Type.STOP) {
return;
}
try {
queue.take();
} catch (InterruptedException e) {
//ignore this
}
}
};
clip.addLineListener(listener );
}
推荐答案
声音片段是一种类型或Line并因此支持Line侦听器。
A sound clip is a type or Line and therefore supports Line listeners.
如果使用addLineListener,则应该在播放开始和停止时获取事件;如果你不在循环中,你应该在剪辑结束时停止。但是,与任何事件一样,在实际播放结束和停止之前可能存在延迟。
If you use addLineListener, you should get events when play starts and stops; if you're not in a loop, you should get a stop when the clip ends. However, as with any events, there might be a lag before the actual end of playback and the stopping.
使方法等待稍微复杂一些。您可以忙着等待它(不是一个好主意)或使用其他同步机制。我认为有一种模式(不确定)等待一个长期操作来抛出一个完成事件,但这是一个普遍的问题,你可能想要单独发布到SO。
Making the method wait is slightly trickier. You can either busy-wait on it (not a good idea) or use other synchronization mechanisms. I think there is a pattern (not sure about it) for waiting on a long operation to throw a completion event, but that's a general question you may want to post separately to SO.
这篇关于我如何等待java声音片段完成播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!