javax.sound.sampled.clip终止播放声音之前
-
21-12-2019 - |
题
我非常困惑,为什么这是直接终止......调试器到目前为止一直没有真正的帮助..我相信代码通过整个方式运行。
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
/**
* An example of loading and playing a sound using a Clip. This complete class
* isn't in the book ;)
*/
public class ClipTest {
public static void main(String[] args) throws Exception {
// specify the sound to play
// (assuming the sound can be played by the audio system)
File soundFile = new File("C:\\Users\\Benny\\Desktop\\AudioSample\\Austin.wav");
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
// due to bug in Java Sound, explicitly exit the VM when
// the sound has stopped.
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.exit(0);
}
}
});
// play the sound clip
clip.start();
}
}
. 解决方案
对生成的调用导致声音在不同的线程上播放,即“Java声音事件调度程序”线程。主线程正常进行,并退出应用程序。
取决于如何和当您想要播放此剪辑时,有不同的解决方案。通常,没有必要的额外预防措施。例如,在游戏中,您想玩游戏声音,但是当游戏退出时,那么应该没有更多的声音。通常,您将 not 从所有人退出应用程序 - 尤其不是任意剪辑完成播放...
但是,在此示例中,您可以使用clip.start()
。
final CountDownLatch clipDone = new CountDownLatch(1);
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
clipDone.countDown();
}
}
});
// play the sound clip and wait until it is done
clip.start();
clipDone.await();
. 不隶属于 StackOverflow