这是我用来播放声音的代码,它非常适合我的需求。我只是不知道如何在需要时停止播放剪辑。
public class Sound {
public Clip play(String filename) {
Clip clip = null;
try {
File file = new File(filename);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.stop();
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
return clip;
}
}
最佳答案
如果您查看 JavaDocs Clip
您应该注意,从 DataLine
继承的方法之一是 stop
Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible. (This doesn't guarantee that there will never be discontinuities beyond the current buffer, of course; if the stopped condition continues for too long, input or output samples might be dropped.) If desired, the retained data can be discarded by invoking the flush method. When audio capture or playback stops, a STOP event is generated.
您可能需要验证这一点,但我似乎理解 start
是一个阻塞方法,也就是说,一旦调用,直到 Clip
完成才会返回玩。这需要在单独的线程
中启动Clip
关于java - 我如何停止播放声音? -Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701280/