-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSoundManager.java
More file actions
85 lines (72 loc) · 2.95 KB
/
Copy pathSoundManager.java
File metadata and controls
85 lines (72 loc) · 2.95 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
/*
* Authors: Jerry Li & Victor Jiang
* Date: June 13, 2025
* Description: This class plays background music and sound effects
*/
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
public class SoundManager {
public Clip currentMusicClip; // To track the currently playing background music
public String currentTrack; // To track which track is currently playing
// Constructor
public SoundManager() {
currentMusicClip = null;
currentTrack = "";
}
// Method to stop the currently playing background music
public void stopBackgroundMusic() {
if (currentMusicClip != null && currentMusicClip.isRunning()) {
currentMusicClip.stop();
currentMusicClip.close();
}
}
// Play background music in loop
public void playBackgroundMusic(String track) {
// If this track is already playing, do nothing
if (track.equals(currentTrack) && currentMusicClip != null && currentMusicClip.isRunning()) {
return;
}
// Stop any currently playing music
stopBackgroundMusic();
File audio_file = null;
AudioInputStream audio_stream = null;
FloatControl volumeControl = null;
float volumeLevel = 0f;
try {
// Load the audio file from the specified path
audio_file = new File("./assets/music/" + track + ".wav");
if (!audio_file.exists()) {
System.err.println("Audio file not found: " + audio_file.getAbsolutePath());
return;
}
audio_stream = AudioSystem.getAudioInputStream(audio_file);
// Create a Clip object to play the audio
currentMusicClip = AudioSystem.getClip();
currentMusicClip.open(audio_stream);
// Set the clip to loop continuously
currentMusicClip.loop(Clip.LOOP_CONTINUOUSLY);
// Adjust the volume of the audio using a FloatControl
volumeControl = (FloatControl) currentMusicClip.getControl(FloatControl.Type.MASTER_GAIN);
// Set appropriate volume level - reduced from -15.0f to -10.0f to make it more audible
volumeLevel = track.equals("gameplay") ? -10.0f : -12.0f; // Gameplay music slightly louder
volumeControl.setValue(volumeLevel);
// Start playing the audio
currentMusicClip.start();
// Keep track of the current track
currentTrack = track;
} catch (Exception e) {
System.out.println("An error occurred while playing background music: " + e.getMessage());
e.printStackTrace();
} finally {
if (audio_stream != null) {
try {
audio_stream.close();
} catch (Exception ignored) {
}
}
}
}
}