Playing Sounds with AudioClip

The sound capabilities of modern computer hardware are usually much more advanced than the dumb terminals of yesterday, and typical users expect their computers to make sounds that are prettier than the coarse console bell. Java programs can do this by loading and playing a file of audio data with the java.applet.AudioClip interface. As the package name implies, the AudioClip interface was originally intended only for applets. Since Java 1.0, applets have been able to call their getAudioClip( ) instance method to read an audio file over the network. In Java 1.2, however, the static java.applet.Applet.newAudioClip( ) method was added to allow any application to read audio data from any URL (including local file: URLs). This method and the AudioClip interface make it very easy to play arbitrary sounds from your programs, as demonstrated by Example 17-2.

Invoke PlaySound with the URL of a sound file as its sole argument. If you are using a local file, be sure to prefix the filename with the file: protocol. The types of sound files supported depend on the Java implementation. Sun’s default implementation supports .wav, .aiff, and .au files for sampled sound, .mid files for MIDI, and even .rmf files for the MIDI-related, proprietary “Rich Music Format” defined by Beatnik.[1]

When you run the PlaySound class of Example 17-2, you may notice that the program never exits. Like AWT applications, programs that use Java’s sound capabilities start a background thread ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.