-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundManager.java
More file actions
101 lines (76 loc) · 2.49 KB
/
Copy pathSoundManager.java
File metadata and controls
101 lines (76 loc) · 2.49 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
101
import javax.sound.sampled.AudioInputStream; // for playing sound clips
import javax.sound.sampled.*;
import java.io.*;
import java.util.HashMap; // for storing sound clips
import java.util.Random; // for random sound selection
public class SoundManager { // a Singleton class
HashMap<String, Clip> clips;
private Clip[] playerHitClips; // array to store player hit sound variations
private Random random; // for random sound selection
private static SoundManager instance = null; // keeps track of Singleton instance
private float volume;
private SoundManager () {
clips = new HashMap<String, Clip>();
random = new Random();
playerHitClips = new Clip[3];
Clip clip = loadClip("backgroundMusic.wav"); // played from start of the game
clips.put("background", clip);
clip = loadClip("shootSound.wav"); // played when the player fires a bullet
clips.put("shoot", clip);
clip = loadClip("explosionSound.wav"); // played when an alien is destroyed
clips.put("explosion", clip);
// Load all three player hit sounds
playerHitClips[0] = loadClip("playerHit1.wav");
playerHitClips[1] = loadClip("playerHit2.wav");
playerHitClips[2] = loadClip("PlayerHit3.wav"); // Note: capital P
clip = loadClip("gameOverSound.wav"); // played when the game is over
clips.put("gameOver", clip);
volume = 1.0f;
}
public static SoundManager getInstance() { // class method to retrieve instance of Singleton
if (instance == null)
instance = new SoundManager();
return instance;
}
public Clip loadClip (String fileName) { // gets clip from the specified file
AudioInputStream audioIn;
Clip clip = null;
try {
File file = new File(fileName);
audioIn = AudioSystem.getAudioInputStream(file.toURI().toURL());
clip = AudioSystem.getClip();
clip.open(audioIn);
}
catch (Exception e) {
System.out.println ("Error opening sound files: " + e);
}
return clip;
}
public Clip getClip (String title) {
return clips.get(title);
}
public void playClip(String title, boolean looping) {
Clip clip = getClip(title);
if (clip != null) {
clip.setFramePosition(0);
if (looping)
clip.loop(Clip.LOOP_CONTINUOUSLY);
else
clip.start();
}
}
public void playRandomPlayerHit() {
int soundChoice = random.nextInt(3);
Clip clip = playerHitClips[soundChoice];
if (clip != null) {
clip.setFramePosition(0);
clip.start();
}
}
public void stopClip(String title) {
Clip clip = getClip(title);
if (clip != null) {
clip.stop();
}
}
}