1

From How can I play sound in Java?

Is it possible to have resouce leakage for the following code? Who will be responsible to close the audio stream?

public static void playAlertSound() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Clip clip = AudioSystem.getClip();
                AudioInputStream inputStream = AudioSystem.getAudioInputStream(Utils.class.getResourceAsStream("/sounds/door_bell.wav"));
                clip.open(inputStream);
                clip.start();
            } catch (Exception e) {
               log.error(null, e);
            }
        }
    }).start();
}
Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

2

You need to explicitly close the line as follows:

clip.addLineListener(new LineListener() {
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            event.getLine().close();
        }
    }
});
Pool
  • 11,999
  • 14
  • 68
  • 78