| Developer's Daily | Java Education |
| front page | java | perl | unix | DevDirectory |
Introduction
We all know that multimedia, used properly, can make any web site more
entertaining. In this article, 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 Java applets is very simple. The
SoundApplet.java code shown in Listing 1 shows the minimal
requirements needed to play a sound file when an applet is downloaded.
Notice that to make the applet easy to hide on a web page, we resized it's
visible dimensions to zero pixels wide, zero pixels tall.
|
import java.applet.*; public class SoundApplet extends Applet { public void init() { super.init();
AudioClip gong = getAudioClip(getDocumentBase(),
"gong.au");
}
|
| Listing 1: | SoundApplet.java - a simple applet that plays the "gong.au" sound file. |
Also notice that there is no path leading to the gong.au file - this 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 applet needs an HTML file to access it, so in Listing 2
we've provided the source code for a bare-bones HTML file that loads the
SoundApplet applet.
|
<HTML>
|
| Listing 2: | SoundApplet.html - a simple HTML file that loads the SoundApplet applet. |
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 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 try the on-line demo of our SoundApplet applet, click here. Of course you can also save the HTML source code once it's loaded into your browser.
Click here to view/download the SoundApplet.java source code.
Finally, click here to download the gong.au
sound file. (You may want to right-click on this link, then select Save Link As ....)
Copyright 1998-2008 DevDaily Interactive, Inc.
All Rights Reserved.