-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSoundUtil.java
60 lines (49 loc) · 1.94 KB
/
SoundUtil.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
public class SoundUtil {
private static Clip clip;
public static Clip playSound(String soundFile, boolean loop) {
return playSoundWithVolume(soundFile, loop, 1.0f);
}
//control volume
public static Clip playSoundWithVolume(String soundFile, boolean loop, float volume) {
try {
File soundPath = new File(soundFile);
if (soundPath.exists()) {
AudioInputStream audioInput = AudioSystem.getAudioInputStream(soundPath);
clip = AudioSystem.getClip();
clip.open(audioInput);
FloatControl volumeControl = null;
try {
volumeControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
float min = volumeControl.getMinimum();
float max = volumeControl.getMaximum();
if (volume < 0.0f) {
volume = 0.0f;
} else if (volume > 1.0f) {
volume = 1.0f;
}
float newVolume = min + (max - min) * volume;
volumeControl.setValue(newVolume);
} catch (IllegalArgumentException e) {
}
if (loop) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
clip.start();
} else {
System.out.println("Cannot find sound file: " + soundFile);
}
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
return clip;
}
public static void stopSound(Clip clip) {
if (clip != null && clip.isRunning()) {
clip.stop();
clip.close();
}
}
}