我正在用 Java build 一架钢琴。我有多个要播放的剪辑,为了节省 RAM,我决定将它们存储在 HashMap 中以供以后使用。但这失败了,它只播放一次,只播放一次。我做错了什么?
来源:
//imports etc.
HashMap<String, Clip> cache = new HashMap<String, Clip>(); //defined as global variable, before the constructor
public void play(String file) {
Clip clip = null;
AudioInputStream audio = null;
if (cache.containsKey(file)) {
clip = cache.get(file);
} else {
audio = AudioSystem.getAudioStream(getClass().getResource("/res/sounds/" + file + ".wav"));
clip = AudioSystem.getClip();
clip.open(audio);
cache.put(file, clip);
}
clip.start();
}
注意:字符串文件
只是.wav的名称,例如“C4”
或“F#5”
。我再次重复一遍,这段代码第一次播放声音,但之后就再也没有播放过。
最佳答案
这是因为 AudioClip
对象从最后播放的帧开始播放。这不会通过调用 start
来重置。
每次想要再次播放该剪辑时,都需要重置它。
if (cache.containsKey(file)) {
clip = cache.get(file);
clip.setFramePosition(0);
}
关于Java 缓存 .wav 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938461/