-
Notifications
You must be signed in to change notification settings - Fork 0
/
SoundController.java
40 lines (35 loc) · 1.19 KB
/
SoundController.java
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
package com.Carlos.spaceinvaders.controller;
import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class SoundController {
private Map<String, Clip> clips = new HashMap<>();
public SoundController() {
loadSound("Shoot", "/sound/Shoot.wav");
loadSound("GameOver","/sound/GameOver.wav");
}
public void loadSound(String name, String filePath) {
try {
InputStream is = getClass().getResourceAsStream(filePath);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(is));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clips.put(name, clip);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
public void playSound(String name) {
Clip clip = clips.get(name);
if (clip != null) {
clip.setFramePosition(0);
clip.start();
}
}
public Map<String, Clip> getClips() {
return clips;
}
}