【发布时间】:2016-06-22 02:56:05
【问题描述】:
我正在尝试打开一个 .wav 文件并使用剪辑播放它。但是当我调用 myClip.open(...) 时,线程冻结并且永远不会恢复。不会抛出任何错误。这是我的代码的简单版本:
try {
AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
myClip = AudioSystem.getClip();
myClip.open(mySound); //This is where it hangs
myClip.start(); //This is never executed
} catch (Exception e) {e.printStackTrace();}
编辑: 我的代码的替代版本(也不起作用):
Clip myClip = null;
new Thread(new Runnable() {
public void run() {
try {
AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
myClip = AudioSystem.getClip();
System.out.println("Before open");
myClip.open(mySound); //This is where it hangs
System.out.println("After open"); //never executed
//This thread runs indefinitely, whether or not clip.start() is called
} catch (Exception e) {e.printStackTrace();}
}
}).start();
try{ Thread.sleep(1000); }catch(Exception e){} //give it a second to open
myClip.start(); //Executed, but doesn't make a sound
System.out.println("Started clip");
输出:
Before open
Started clip
我知道是什么原因造成的,但我想不出办法让线程永远冻结。它冻结是因为我计算机上的声音驱动程序偶尔会停止工作,并阻止任何程序的任何声音播放。我只需要一些方法来强制 clip.open 方法(或线程)在大约 2 到 3 秒后超时。 在另一个线程中调用 clip.start() 可以工作,但由于剪辑尚未打开,因此不会播放任何声音。并且包含 clip.open(...) 的线程将永远运行,即使在调用 clip.start() 之后也是如此。
【问题讨论】:
-
尝试写在一个线程中。否则它会阻塞你的主线程,感觉就像冻结一样。
标签: java audio freeze javax.sound.sampled