Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Load Images and Play Sounds in Java Applets  : Page 3

Embed Java applets that load images and play sounds into your Web pages.


advertisement
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: play(),loop(), and stop().

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 play() and 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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date