-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundManager.java
More file actions
100 lines (85 loc) · 2.85 KB
/
SoundManager.java
File metadata and controls
100 lines (85 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import java.io.File;
import java.util.HashMap;
// Sound clip management with singleton pattern.
public class SoundManager {
private static SoundManager instance = null;
public HashMap<String, Clip> clips;
private SoundManager() {
clips = new HashMap<String, Clip>();
// Load sound clips
loadClip("footstep", "sounds/runningOnGrass.wav");
loadClip("coinPickup", "sounds/coinPickp.wav");
loadClip("background", "sounds/backgroundMusic.wav");
}
public static SoundManager getInstance() {
if (instance == null) {
instance = new SoundManager();
}
return instance;
}
private void loadClip(String name, String filename) {
try {
File file = new File(filename);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file.toURI().toURL());
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clips.put(name, clip);
} catch (Exception e) {
System.out.println("Error loading sound: " + filename + " - " + e);
}
}
public void playClip(String name, boolean looping) {
Clip clip = clips.get(name);
if (clip != null) {
clip.setFramePosition(0);
if (looping) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
} else {
clip.start();
}
}
}
public void stopClip(String name) {
Clip clip = clips.get(name);
if (clip != null) {
clip.stop();
}
}
public void stopAll() {
for (Clip clip : clips.values()) {
clip.stop();
}
}
public boolean isPlaying(String name) {
Clip clip = clips.get(name);
return clip != null && clip.isRunning();
}
public void startFootstep() {
if (!isPlaying("footstep")) {
playClip("footstep", true);
}
}
public void stopFootstep() {
stopClip("footstep");
}
public void playBackgroundMusic() {
Clip clip = clips.get("background");
if (clip != null) {
// Set volume to 60% (0.6f)
FloatControl volumeControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
if (volumeControl != null) {
// Convert 0.6f to decibels
float volume = 0.6f;
float dB = (float) (20 * Math.log10(volume));
volumeControl.setValue(dB);
}
// Reset to beginning and play in loop
clip.setFramePosition(0);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
}