我正在尝试使用以下代码播放 .wav 文件:
public class AudioTest {
public AudioTest() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
System.out.println(classLoader.getResourceAsStream("sound.wav"));//to see if the sound file is found
try{
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(classLoader.getResourceAsStream("sound.wav"));
clip.open(inputStream);
clip.start();
while (!clip.isRunning())
Thread.sleep(10);
while (clip.isRunning())
Thread.sleep(10);
clip.close();
} catch (Exception e)
{
System.out.println("something failed");
}
System.out.println("done"); //to see if the sound is finished playing
}
}
这有效,但如果我离开:
while (!clip.isRunning())
Thread.sleep(10);
while (clip.isRunning())
Thread.sleep(10);
clip.close();
不播放声音。我看到的几乎所有播放 .wav 文件的例子都没有那个部分。出了什么问题,有没有更优雅的方法来解决这个问题?