forked from tapickell/JavaStuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundClip.java
More file actions
executable file
·98 lines (81 loc) · 2.8 KB
/
Copy pathSoundClip.java
File metadata and controls
executable file
·98 lines (81 loc) · 2.8 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
//SoundClip encapsulates the Java Sound API classes needed to
//load and play a sound file (AIFF, AU, or WAV). The sound file
//is not streamed or tracked so this class should only be used for
//smallish sound files that can be quickly loaded by an applet.
import javax.sound.sampled.*;
import java.io.*;
import java.net.*;
public class SoundClip {
//the source for audio data
private AudioInputStream sample;
//sound clip property is read-only here
private Clip clip;
public Clip getClip() { return clip; }
//looping property for continuous playback
private boolean looping = false;
public void setLooping(boolean _looping) { looping = _looping; }
public boolean getLooping() { return looping; }
//repeat property used to play sound multiple times
private int repeat = 0;
public void setRepeat(int _repeat) { repeat = _repeat; }
public int getRepeat() { return repeat; }
//filename property
private String filename = "";
public void setFilename(String _filename) { filename = _filename; }
public String getFilename() { return filename; }
//property to verify when sample is ready
public boolean isLoaded() {
return (boolean)(sample != null);
}
//constructor
public SoundClip() {
try {
//create a sound buffer
clip = AudioSystem.getClip();
} catch (LineUnavailableException e) {
}
}
//this overloaded constructor takes a sound file as a parameter
public SoundClip(String audiofile) {
this(); //call default constructor first
load(audiofile); //now load the audio file
}
//***************
private URL getURL(String filename) {
URL url = null;
try {
url = this.getClass().getResource(filename);
}
catch (Exception e) { }
return url;
}
//load sound file
public boolean load(String audiofile) {
try {
//prepare the input stream for an audio file
setFilename(audiofile);
//***************
sample = AudioSystem.getAudioInputStream(getURL(filename));
//load the audio file
clip.open(sample);
return true;
} catch (IOException e) {
return false;
} catch (UnsupportedAudioFileException e) {
return false;
} catch (LineUnavailableException e) {
return false;
}
}
public void play() {
//exit if the sample hasn't been loaded
if (!isLoaded()) return;
//reset the sound clip
clip.setFramePosition(0);
//play sample with optional looping
if (looping)
clip.loop(Clip.LOOP_CONTINUOUSLY);
else
clip.loop(repeat);
}
}