Playing Sound Files
The standard Java classes provide two basic ways of playing sound fi les (otherwise
known as audio clips):
the play method of class Applet (from the java.applet package);
the play method of the AudioClip interface (also from the applet package).
The former should be used for a sound that is to be played just once from an
applet. For a sound that is to be played more than once or a sound that is to be played
from an application (rather than from an applet), an AudioClip reference should be
used. Since we shall be concerned only with applications in this chapter, no further
mention will be made of the play method of class Applet here.
It may seem strange to use a class from package applet within an application, but
AudioClip allows us to do just this. What is even stranger is that we use a method of
class Applet to generate the AudioClip object! Method newAudioClip of class Applet
takes a URL as its single argument and generates the required AudioClip object. The
reason that we are able to use this class in an application, of course, is that it is a
static method (and so can be used without the creation of an Applet object). Here
is the signature for method newAudioClip :
public static fi nal AudioClip newAudioClip(URL url)
The fact that a URL has to be supplied as the argument does not mean that we
must refer to a remote fi le (though we can, as will be seen with applets in the next
chapter). We can refer to a local fi le by supplying a URL that uses the fi l e protocol.
AudioClip clip =
(Note the use of the Applet class name, since the method is static.)
Once the clip has been created, the following three methods are available and
serve purposes that are self-evident from their names:
void play() ;
void stop() ;
void loop() .
These three methods may then be made use of in a Java GUI by associating them
with different buttons.
This simple example provides three buttons that will allow the user to play, stop and
continuously loop through a specifi ed sound fi le. (The third option is likely to get
annoying pretty quickly!) The code is very straightforward and requires almost no