-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSoundPlayer.java
60 lines (46 loc) · 1.59 KB
/
SoundPlayer.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
60
package io;
import java.applet.Applet;
import java.applet.AudioClip;
import java.lang.IllegalArgumentException;
/**
* SoundPlayer.java plays simple .wav files for sound effects.
* should only be used to play short sounds because each
* sound is fully loaded into memory and kept there for rapid replay.
* Large sound files such as songs, should be streamed, not fully read into memory and then fully played.
* SoundPlayer supports only linear PCM audio files.
* If SoundPlayer is given a .wav file that is not in the simple linear PCM format,
* then there will not be an error thrown, but no sound will play.
* @author Ederin Igharoro
* @author Max Barnhart
*/
public class SoundPlayer
{ private AudioClip soundEffect; // Sound player
public SoundPlayer(String wavfile) throws Exception
{
//Note: if wavfile is null, then this will through a NullPointerException
if (!wavfile.endsWith(".wav") && !wavfile.endsWith(".WAV"))
{ throw new IllegalArgumentException("SoundPlayer(): File name must end with .wav");
}
try
{
soundEffect = Applet.newAudioClip(this.getClass().getResource(wavfile));
System.out.println("SoundPlayer("+wavfile+")");
}
catch (Exception e)
{ throw new IllegalArgumentException("SoundPlayer(): Cannot open file:"+wavfile);
}
}
//Plays in a new thread
public void play()
{ //System.out.println("soundEffect="+soundEffect.toString());
soundEffect.play(); // Play only once
}
public void stop()
{
soundEffect.stop();
}
public void loop()
{
soundEffect.loop();
}
}