gpt4 book ai didi

java - 我怎样才能等待 java 声音剪辑完成播放?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:00 25 4
gpt4 key购买 nike

我正在使用以下代码通过 java 声音 API 播放声音文件。

    Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream);
clip.open(inputStream);
clip.start();

Clip.start() 方法调用立即返回,系统在后台线程中播放声音文件。我希望我的方法暂停,直到播放完成。

有什么好的方法吗?

编辑:对于所有对我的最终解决方案感兴趣的人,根据 Uri 的回答,我使用了以下代码:

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 );
}

最佳答案

我更喜欢 Java 8 中的这种方式:

CountDownLatch syncLatch = new CountDownLatch(1);

try (AudioInputStream stream = AudioSystem.getAudioInputStream(inStream)) {
Clip clip = AudioSystem.getClip();

// Listener which allow method return once sound is completed
clip.addLineListener(e -> {
if (e.getType() == LineEvent.Type.STOP) {
syncLatch.countDown();
}
});

clip.open(stream);
clip.start();
}

syncLatch.await();

关于java - 我怎样才能等待 java 声音剪辑完成播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/557903/

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