Recipe 13.9 Playing a Sound File


You want a quick and easy way to "make noise" or play an existing sound file.


Get an AudioClip object and use its play( ) method.


This might seem out of place in the midst of all this Graphics code, but there's a pattern. We're moving from the simpler graphical forms to more dynamic multimedia. You can play a sound file using an AudioClip to represent it. Back in the days of 1.0 and 1.1, you could do this only in an applet (or using unsupported classes). But starting with JDK 1.2, this capability was extended to applications. Here is a program that plays either two demonstration files from a precompiled list or the list of files you give. Due to the applet legacy, each file must be given as a URL:

import java.applet.*; import*; /** Simple program to try out the "new Sound" stuff in JDK1.2 --  * allows Applications, not just Applets, to play Sound.  */ public class SoundPlay {     static String defSounds[] = {         "file:///javasrc/graphics/test.wav",         "file:///music/midi/Beet5th.mid",     };     public static void main(String[] av) {         if (av.length == 0)             main(defSounds);         else for (int i=0;i<av.length; i++) {             System.out.println("Starting " + av[i]);             try {                 URL snd = new URL(av[i]);                 // open to see if works or throws exception, close to free fd's                 // snd.openConnection( ).getInputStream( ).close( );                 Applet.newAudioClip(snd).play( );             } catch (Exception e) {                 System.err.println(e);             }          }         // With this call, program exits before/during play.         // Without it, on some versions, program hangs forever after play.         // System.exit(0);     } }

As the code comment reports, you can open the URL to see if it succeeds; if it throws an IOException, there is not much point in trying the newAudioClip( ) call, and catching it this way might allow you to print a better error message.

See Also

There are several limitations on the applet sound API. The JMFPlayer interface discussed in Recipe 13.10 plays sound files with a volume control panel.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: