来自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();
}
答案 0 :(得分:2)
您需要按如下方式明确关闭该行:
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});