We all know that multimedia, used properly, can make any web site more entertaining. In this applet tutorial, we'll present a brief example of a Java applet that plays a sound file when it is downloaded. The compiled applet class file is very small - only 559 bytes - and can be downloaded quickly into a user's web browser.
The SoundApplet applet
Fortunately, using sounds in a Java applet is very simple. The JavaSoundApplet.java
source code shown below demonstrates the minimal requirements needed to play a sound file when a Java applet is downloaded.
Notice that to make this Java applet easy to hide on a web page, we resized it's visible dimensions to zero pixels wide, zero pixels tall.
import java.applet.*; /** * JavaSoundApplet.java - an example java applet that plays * the "gong.au" sound file when the applet is loaded. */ public class JavaSoundApplet extends Applet { public void init() { super.init(); // set the applet size resize(0,0); // load the sound file and then play it AudioClip gong = getAudioClip(getDocumentBase(), "gong.au"); gong.play(); } }
As you can see from our Java applet example, there are really only two steps required to play a sound in a Java applet: (1) loading the sound file into an AudioClip
object, and (2) playing the sound using the play()
method of the AudioClip
class.
Also notice that there is no path leading to the gong.au file -- the applet expects to find the gong.au file in the same directory as the class file. If instead the gong.au file was located in a sub-directory named sounds, the file would have been loaded with this statement:
AudioClip gong = getAudioClip(getDocumentBase(), "sounds/gong.au");
The SoundApplet.html HTML file
Every Java applet needs an HTML file to access it, so in the next listing we've provided the source code for a bare-bones HTML file that loads the SoundApplet
applet.
<!-- SoundApplet.html - a simple HTML file that loads the SoundApplet applet. --> <HTML> <HEAD> <TITLE>SoundApplet Demo</TITLE> </HEAD> <BODY> <APPLET CODE="SoundApplet.class" height="0" width="0"></APPLET> </BODY> </HTML>
Notice in this listing that nothing special is required, other than the use of the <APPLET>
tag. This tag simply gives your browser the information it needs to load the Java SoundApplet
class file. Your browser takes care of the rest of the work.
Try the on-line demo, and download the source
If you'd like to see the applet from this tutorial running, check out our Java sound applet demo. Of course you can also save the HTML source code once it's loaded into your browser.
You can also download our SoundApplet.java applet source code.
Finally, click here to download the gong.au applet sound file. (You may want to right-click on this link, then select Save Link As ...)