-1
    public static void main(String[] args) {
        try{
            File file = new File("audiodata/test.wav");
            AudioInputStream ain = AudioSystem.getAudioInputStream(file);

            AudioFormat format = ain.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);

            clip.start();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

I have written this simple main method to play the sound file, but it does not work. There is no Exception thrown. The program ends and I cannot hear anything. I have no idea, what my mistake is. Also creating the Clip by AudioSystem.getClip(); does not change anything.

  • 1
    You are just starting the clip playing, one way or another you have to wait until it finishes playing. Currently you are just exiting before it has had a chance to get going. – greg-449 Jun 07 '17 at 13:46

1 Answers1

0

The correct way to wait for a sound to finish playing is with a concurrency class like CountDownLatch, or with lower-level concurrency operations like wait/notify or Locks:

Clip clip = (Clip) AudioSystem.getLine(info);

CountDownLatch doneLatch = new CountDownLatch(1);

clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType().equals(LineEvent.Type.STOP)) {
            doneLatch.countDown();
        }
    }
});

clip.open(ain);
clip.start();

doneLatch.await();
VGR
  • 40,506
  • 4
  • 48
  • 63