-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlaySound.java
More file actions
74 lines (65 loc) · 1.84 KB
/
Copy pathPlaySound.java
File metadata and controls
74 lines (65 loc) · 1.84 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
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;
/**
* @author Jason/Ge Wu
* @since 2017-10-09
*/
public class PlaySound
{
private static String soundPath;
public static String getSoundPath() { return soundPath; }
public static void setSoundPath(final String soundPath)
{
PlaySound.soundPath = soundPath;
File path = new File(soundPath);
if(!path.exists())
throw new IllegalArgumentException("File Does Not Exist");
}
private static PlaySound instance;
public static PlaySound getInstance()
{
if(instance == null)
{
synchronized (PlaySound.class)
{
if (instance == null) {
instance = new PlaySound(soundPath);
}
}
}
return instance;
}
private PlaySound(String sound)
{
if(soundPath == null)
throw new IllegalArgumentException("Invalid Sound Path, Invoke setSoundPath First");
}
public void play(final String path)
{
File sound;
try {
sound = new File(path).getAbsoluteFile();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(sound);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("-> Play Sound @ " + path + "Failed: " + ex.getMessage());
}
}
public void play(String... paths)
{
if(paths.length == 0)
{
play(soundPath);
}
for(String path : paths)
{
play(path);
}
}
}