我正在写一个视频游戏,我想在玩家输掉或退出(到主菜单)时停止音乐。
这是我的代码:
public class Music{
private static Clip clip;
private static AudioInputStream stream;
private static void loadMusic(){
if(clip != null) return;
try {
AudioFormat format;
DataLine.Info info;
stream = AudioSystem.getAudioInputStream(Music.class.getResource("/resources/music/music.wav"));
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void playMusic(boolean loop){
loadMusic();
if(clip == null) return;
if(loop) clip.loop(Clip.LOOP_CONTINUOUSLY);
else clip.start();
}
public static void stopMusic(){
clip.stop();
clip.setMicrosecondPosition(0);
}
}
每当我调用 Music.stopMusic() 时,游戏都会挂起几秒钟然后继续。