我想打開一個.wav文件,並使用剪輯播放它。但是,當我打電話myClip.open(...),線程凍結,永遠不會恢復。沒有錯誤被拋出。下面是我的一個簡單的代碼版本:Java的clip.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.start()之後,包含clip.open(...)的線程也會永久運行。
嘗試寫入一個線程。否則,它會阻止你的主線程,感覺像凍結。 – Boola