Playing a Sound File

Problem

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

Solution

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

Discussion

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 sun.java classes). But with Java 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 java.net.*;

/** 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 this 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 Section 12.9 plays sound files with a volume control panel.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.220