Question

I am so confused as to why this is terminating straight away... The debugger so far has been no real help.. I am sure the code is running the whole way through.

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

/**
 * An example of loading and playing a sound using a Clip. This complete class
 * isn't in the book ;)
 */
public class ClipTest {

  public static void main(String[] args) throws Exception {

    // specify the sound to play
    // (assuming the sound can be played by the audio system)
    File soundFile = new File("C:\\Users\\Benny\\Desktop\\AudioSample\\Austin.wav");
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);
    // due to bug in Java Sound, explicitly exit the VM when
    // the sound has stopped.
    clip.addLineListener(new LineListener() {
      public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
          event.getLine().close();
          System.exit(0);
        }
      }
    });
    // play the sound clip
    clip.start();
  }
} 
Was it helpful?

Solution

The call to clip.start() causes the sound to be played on a different thread, namely on the "Java Sound Event Dispatcher" thread. The main thread proceeds normally, and the application is exited.

Depending on how and when exactly you want to play this clip, there are different solutions. Quite often, there are no additional precautions necessary. For example, in a game, you want to play in-game sounds, but when the game exits, then no more sounds should be played. And usually, you will not exit the application with System.exit(0) at all - and especially not after an arbitrary clip has finished playing...

However, in this example, you might use a CountDownLatch.

final CountDownLatch clipDone = new CountDownLatch(1);
clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            event.getLine().close();
            clipDone.countDown();
        }
    }
});
// play the sound clip and wait until it is done
clip.start();
clipDone.await();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top