3

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?

Lucivius
  • 83
  • 4
  • 2
    Have you tried implementing a `LineListener` as suggested in this SO answer? http://stackoverflow.com/questions/577724/trouble-playing-wav-in-java/577926#577926 – Dan W Dec 14 '12 at 23:52

0 Answers0