Tow*_*ni0 3 java audio javasound clip try-with-resources
我正在为我的学校项目重写我的 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 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();
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
问题是当块完成导致播放停止时,try-with-resources块将自动关闭其中Clip创建的。
在您的另一个示例中,由于您没有手动关闭它,因此可以继续播放。
如果你想Clip在它播放完后关闭它,你可以用LineListener它添加一个,addLineListener()并在你收到这样的STOP事件时关闭它:
final Clip clip = AudioSystem.getClip();
// Configure clip: clip.open();
clip.start();
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
Run Code Online (Sandbox Code Playgroud)