Comp202: Principles of Object-Oriented Programming II
Fall 2006 -- Hangman Project: Adding a Simple Sound to a Java Program   

Quick links to supporting pages:  Main page, BodyParts, MVC, View & controller, WordList

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.


Last Revised Thursday, 03-Jun-2010 09:52:20 CDT

©2006 Stephen Wong and Dung Nguyen