播放Wav声音示例代码中的资源泄漏

时间:2009-12-28 17:31:10

标签: java audio

来自How can I play sound in Java?

以下代码是否可能有资源泄漏?谁将负责关闭音频流?

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();
}

1 个答案:

答案 0 :(得分:2)

您需要按如下方式明确关闭该行:

clip.addLineListener(new LineListener() {
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            event.getLine().close();
        }
    }
});