我正在为我的学校项目重写我的 AudioManager 课程,但遇到了一个问题。我的教授告诉我使用 Try-with-resources 块而不是使用 try/catch 加载我的所有资源(参见下面的代码)。我正在使用 javax.sound.sampled.Clip 中的 Clip 类,如果我不 close() Clip,一切都与我的 PlaySound(String path) 方法完美配合,该方法使用 try/catch/。我知道如果我关闭()剪辑我不能再使用它了。我已阅读有关 Clip 和 Try-with-resources 的 Oracle 文档,但找不到解决方案。所以我想知道的是:
是否可以使用 Try-with-resource 块在剪辑关闭之前播放/收听剪辑中的声音?
// Uses Try- with resources. This does not work.
public static void playSound(String path) {
try {
URL url = AudioTestManager.class.getResource(path);
try (Clip clip = AudioSystem.getClip()){
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.start();
}
} catch( LineUnavailableException | UnsupportedAudioFileException | IOException e) {
e.printStackTrace();}
}
// Does not use Try- with resources. This works.
public static void playSound2(String path) {
Clip clip = null;
try {
URL url = AudioTestManager.class.getResource(path);
clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.start();
}
catch( LineUnavailableException | UnsupportedAudioFileException | IOException e) {
e.printStackTrace();}
finally {
// if (clip != null) clip.close();
}
}
提前致谢!