
362
|
Chapter 10, Audio
#70 Play a Sound in an Applet
HACK
The last three buttons—Play, Stop, and Loop—are handled trivially in
actionPerformed( ) with calls to the Applet methods play( ), stop( ), and
loop( )
, respectively.
I’ve also provided a
main( )
method here. Applets don’t need them, but since
an applet is just a
JPanel
, why not just put it in a
JFrame
and run it, right?
What’s the worst that could happen?
No Browser, No Sound
Since there’s a main( ) method, just type java AppletAudio on the command
line and the applet will come up in its own frame, as seen in Figure 10-1.
Click the File button and choose a file to have its URL placed in the field.
Now, click Play.
Nothing happens. If you have an output console, you should see something
like:
java.lang.NullPointerException
at java.applet.Applet.getAppletContext(Applet.java:171)
at java.applet.Applet.getAudioClip(Applet.java:279)
at AppletSound.actionPerformed(AppletSound.java:71)
at javax.swing.AbstractButton.fireActionPerformed(
AbstractButton.java:1819)
...
I’ll save you the time of typing a URL by hand and hitting Load; the same
thing happens.
What’s happening is that the implicit call to
getAppletContext( ) is failing
because there is no applet context; i.e., the environment in which the applet
is executed. An applet expects to run in a browser or something similar that
provides access to cached images and sounds and the ability to get docu-
ments ...