我正在制作游戏扩展来播放一些声音。声音可能会在随机时间触发,这意味着相同的声音可能会在相隔很短的时间内触发两次。在这种情况下,声音应该开始播放,即使它已经在播放(如果这有意义的话)。
我正在使用 Clip 来播放声音。这意味着我必须在播放之前“倒带”剪辑。看来,由于是同一个剪辑,它在重新开始之前就停止了播放。我想要的是它继续播放,并在上一个剪辑的“顶部”播放相同的剪辑。请参阅此示例:
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaApplication {
public static void main(String[] args) throws Exception {
File file = new File(JavaApplication.class.getResource("1.wav").getPath());
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.setFramePosition(0);
clip.start(); // The sound is 300 ms long
Thread.sleep(150); // Let it play for 150 ms
clip.setFramePosition(0); // Attempt to start it from the beginning, without stopping it
clip.start();
Thread.sleep(1000);
}
}
最佳答案
您是否尝试过在需要时创建重复对象并在完成时销毁它?一个新的 Clip 对象,或者只是复制原始对象并让它一起播放。
Clip temp = clip;
temp.start(); // The sound is 300 ms long
Thread.sleep(150); // Let it play for 150 ms
temp = null;
只是一个建议,您也可以尝试使用 Clip[] 数组来处理在不同时间播放的几个剪辑。
关于java - 如何启动已经在播放的声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38610986/