import java.applet.AudioClip;
/** This class represents a sound clip that extends the functionality
* of the Java Applet AudioClip class.
*
*
TimedAudioClip objects can be played just like regular
* AudioClip objects. The call to play() returns
* immediately. TimedAudioClip has the additional feature that
* it can be played using the playAndWait() method, which will not
* return until the clip has entirely finished playing.
*
*
The ability to play and wait can be a useful feature when one wants the
* execution of the program to pause until the sound clip has finished for
* some reason. The way the TimedAudioClip object knows how long
* it takes to play itself is by the passing of a duration field to its
* constructor.
*/
public class TimedAudioClip implements AudioClip {
private AudioClip myClip;
private long myPlayTime, myDuration;
private boolean myIsLooping = false;
/** Constructs a new TimedAudioClip to play the given
* AudioClip, which is the given duration in length.
*
* @param clip The AudioClip to play; may not be null.
* @param duration The length in milliseconds of the given clip;
* may not be less than zero.
*/
public TimedAudioClip(AudioClip clip, long duration) {
if (clip == null)
throw new IllegalArgumentException("null AudioClip passed");
else if (duration < 0)
throw new IllegalArgumentException("negative duration passed");
else {
myClip = clip;
myDuration = duration;
}
}
/** Constructs a new TimedAudioClip to play the given AudioClip;
* since no duration is passed, it is assumed to be 0ms, and the clip does
* not wait if its playAndWait method is called.
*/
public TimedAudioClip(AudioClip clip) {
this(clip, 0);
}
/** Plays this TimedAudioClip; returns instantly. */
public void play() {
myPlayTime = System.currentTimeMillis();
myClip.play();
}
/** Begins repeated playing of this TimedAudioClip. Returns instantly. */
public void loop() {
myIsLooping = true;
myClip.loop();
}
/** Halts the playing and/or looping of this TimedAudioClip. */
public void stop() {
myIsLooping = false;
myClip.stop();
}
/** Plays this TimedAudioClip; does not return until playing has completed. */
public void playAndWait() {
play();
while (isPlaying())
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
break;
}
}
/** Returns this TimedAudioClip's base AudioClip object.
* @return this TimedAudioClip's base AudioClip object.
*/
public AudioClip getClip() {
return myClip;
}
/** Returns this TimedAudioClip's duration in milliseconds.
* @return this TimedAudioClip's duration in milliseconds.
*/
public long getDuration() {
return myDuration;
}
/** Returns whether or not this TimedAudioClip is currently
* playing. The value will be false unless the TimedAudioClip
* has been played recently and has not yet finished.
* @return whether or not this TimedAudioClip is currently playing.
*/
public boolean isPlaying() {
return myIsLooping || myPlayTime + myDuration > System.currentTimeMillis();
}
}