The Sounds of Multimedia
Learning how to play sounds will take your program a step closer to true multimedia. Fortunately, Java provides a java.applet.AudioClip class that does all the work for you with its three functions:
As always, you first must make an instance of the AudioClip class before using it in your programs. Also, you can make multiple AudioClip objects and even have them play at the same time if you like. The resulting sound is mixed together to produce a composite. However, depending on your individual sounds, this doesn't necessarily mean it will be a musical composite.
Just like with
getImage(), you can use a method called
getAudioClip(), which the Applet class provides, to load your sound clip into memory. You can see this method in Listing 3 (the HTML code is in Listing 4).
First, you declare a variable of type AudioClip, letting the user pass in the name of the audio file as a parameter. You did the same with the image. Second, you play your sound when the user clicks the mouse. Sounds play asynchronously, which means the program keeps running while the sound is playing. It doesn't have to wait for the sound to finish, presenting the appearance that the sound is being played at the same time the picture is being drawn.
In Listings 3 and 4, notice that you call the audio object's
stop() methods. You need to use
play() to play the sound that has been loaded, and the
stop() is just a safeguard in case the sound is still playing when the program goes into the event handler again. This can easily happen if the sound clip is long or the user clicks the mouse in very rapid succession.