音频剪辑不会连续循环
问题描述:
有人能指出正确的方向,为什么这段代码不能连续播放这个音频片段?它播放一次并停止。
Can anyone point me in the right direction as to why this code will not play this audio clip continuously? It plays it once and stops.
final Clip clip = AudioSystem.getClip();
final AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("Alarm_Police.wav"));
clip.open(inputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
答
如果您正在运行更大的应用程序,这个答案可能是不适用。但是对于仅使用那段代码的简单测试,这可能帮助:
If you are running a bigger application, this answer may not apply. But for a simple test with only that piece of code, this may help:
Clip.loop()启动它自己的线程,但是线程不会使JVM保持活动状态。因此,为了使其工作,请确保剪辑不是唯一的线程。
Clip.loop() starts it's own thread, but that thread will not keep the JVM alive. So to make it work, make sure the clip is not the only thread.
如果我从这个片段中遗漏Thread.sleep(..),我会遇到与你相同的问题;
If I leave out Thread.sleep(..) from this snippet, I get the same issue as you;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Snippet {
public static void main(String[] args) throws Exception {
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("notify.wav"));
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
Thread.sleep(10000); // looping as long as this thread is alive
}
}