我正在尝试打开一个 .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() 之后也是如此。