Adding a Simple Sound to a Java Program

Use the techiques below to create the Announcer class, which should have obvious usage in the HangmanFrame's win() and lose() methods.

Java can play either AU or WAV files.

Be sure to put your audio files in the appropriate package under the "classes" directory!

To play a beep:

Simply call


The Toolkit is a collection of useful methods for the AWT.   Since it is system dependent, the static getDefaultToolkit() method returns the toolkit appropriate for the program's run-time environment.   It is a static Toolkit factory.

Supported File types:

Java supports the following audio file types for creating an AudioClip:

To play an Audio files from an Applet:

Let "applet" be a reference to the applet itself:

    AudioClip myAudioClip = applet.getAudioClip(applet.getCodeBase(),"");;

This only works from inside an applet.

To Play Audio Files from an Application

Use the Applet's static methods to bring in an audio file.   Note that the exception must be caught or thrown.   The [soundfile directory] is relative to the default directory.

AudioClip soundClip;

File file = new File([sound file directory] + [soundfile]);

    soundClip = Applet.newAudioClip(file.toURL());
catch (MalformedURLException mfe) {}

To play the sound:;

When running the application from inside JBuilder, the sound file directory is relative to the JBuilder working directory.   On the other hand, when running the application from the command line, the sound file directory is relative to the default Java directory.    If you have not set the the JBuilder working directory to be the "classes" sub-directory, then the program will not run under both JBuilder and the command line.