|
Previous Next
Using the AudioClip class in the Applet
In the following example, SoundWhistle.java, we will use the init and the paint methods for Applets. We are going to use the AudioClip class to play sounds. We define the variable beep as type AudioClip in the beginning of the Applet.
In the init method, we create an audio clip by calling getAudioClip where we tell it the name and location of the sound file. The JApplet getCodeBase() method picks up the directory from where the applet is running. So here "whistle.wav" is assumed to be in the same directory as the applet.
In the paint method, we print out "Playing the whistle ..." on the applet at the coordinates x=15 and y=10. Then we play the AudioClip. Note that when we go to another application that hides this applet, and then return, the whistle sounds again because the paint is re-executed when the applet is re-displayed.
The HTML code to run the SoundWhistle.class follows.
<applet code="SoundWhistle.class" height="50" width="200">
</applet>
The source for SoundWhistle.java follows.
import java.awt.*;
import java.applet.AudioClip;
public class SoundWhistle extends javax.swing.JApplet {
AudioClip beep;
public void init() {
beep = getAudioClip(getCodeBase(), "whistle.wav");
}
public void paint(Graphics screen) {
screen.drawString("Playing the whistle ...", 15, 10);
if (beep != null)
beep.play();
}
}
In the next example, SoundTrain.java, we create an applet similar to the above except we will add the stop method. We will need the applet's stop method because we will pay our AudioClip continuously in a loop. If we don't stop the AudioClip in our stop method, it will run after the applet has been stopped. To stop it, you would have to close all windows in the browser.
There is not much change in our init method. In the paint method, we print out "Playing the train ..." on the applet at the coordinates x=10 and y=30. Then we play the AudioClip in a loop using the AudioClip's loop method. In the JApplet's stop method, we use the AudioClip's stop method to discontinue the sound. There is a check to make sure that the sound has had a chance to at least get started, "if (trainSound != null)". An object that has been declared but not initialized will have a value of null.
The HTML code to run the SoundTrain.class follows.
<applet code="SoundTrain.class" height="50" width="200">
</applet>
The source for SoundTrain.java follows.
import java.awt.*;
import java.applet.AudioClip;
public class SoundTrain extends javax.swing.JApplet {
AudioClip trainSound;
public void init() {
trainSound = getAudioClip(getCodeBase(),"train.wav");
}
public void stop() {
if (trainSound != null)
trainSound.stop();
}
public void paint(Graphics screen) {
screen.drawString("Playing the train ...", 10, 30);
if (trainSound != null)
trainSound.loop();
}
}
Previous Next
|