I'm trying to play a .wav file with this code:
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
}
}
This works, but if i leave the:
while (!clip.isRunning())
Thread.sleep(10);
while (clip.isRunning())
Thread.sleep(10);
clip.close();
part out the sound isn't played. Almost all examples i saw of playing a .wav file didn't have that part. What goes wrong and is there a more elegant wat to fix this?