You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.8 KiB
69 lines
1.8 KiB
package cn.edu.caztc.sokobangame;
|
|
|
|
import javax.sound.sampled.*;
|
|
import java.io.File;
|
|
|
|
public class MusicPlayer {
|
|
private static MusicPlayer instance;
|
|
private Clip clip;
|
|
private int currentTrackIndex = -1;
|
|
private boolean isMuted = true;
|
|
|
|
public int getCurrentTrackIndex() {
|
|
return currentTrackIndex;
|
|
}
|
|
|
|
private MusicPlayer() {}
|
|
|
|
public static synchronized MusicPlayer getInstance() {
|
|
if (instance == null) {
|
|
instance = new MusicPlayer();
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
public void playMusic(int index) {
|
|
if (index < 0 || index >= MapConfig.MUSIC_FILES.length) return;
|
|
|
|
stopMusic();
|
|
currentTrackIndex = index;
|
|
isMuted = false;
|
|
|
|
try {
|
|
AudioInputStream audioInput = AudioSystem.getAudioInputStream(
|
|
new File(MapConfig.MUSIC_PATH + MapConfig.MUSIC_FILES[index]));
|
|
clip = AudioSystem.getClip();
|
|
clip.open(audioInput);
|
|
clip.loop(Clip.LOOP_CONTINUOUSLY);
|
|
clip.start();
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public void stopMusic() {
|
|
if (clip != null && clip.isRunning()) {
|
|
clip.stop();
|
|
clip.close();
|
|
}
|
|
isMuted = true;
|
|
}
|
|
|
|
public void toggleMute() {
|
|
if (isMuted) {
|
|
playMusic(currentTrackIndex);
|
|
} else {
|
|
stopMusic();
|
|
}
|
|
}
|
|
|
|
public void nextTrack() {
|
|
if (currentTrackIndex == -1) return;
|
|
int newIndex = (currentTrackIndex + 1) % MapConfig.MUSIC_FILES.length;
|
|
playMusic(newIndex);
|
|
}
|
|
|
|
public boolean isMuted() {
|
|
return isMuted;
|
|
}
|
|
} |