我正在为我的学校项目重写我的 AudioManager 类,但遇到了一个问题。我的教授告诉我使用 Try-with-resources 块加载我的所有资源,而不是使用 try/catch(请参阅下面的代码)。我正在使用 javax.sound.sampled.Clip 中的 Clip 类,一切都与我的 PlaySound(String path) 方法完美配合,该方法使用 try/catch/ 如果我不 close() 剪辑。我知道如果我 close() 剪辑我不能再使用它。我已阅读 Oracle Docs for Clip 和 Try-with-resources,但找不到解决方案。所以我想知道的是:
是否可以使用 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 …Run Code Online (Sandbox Code Playgroud)