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, ...

Get Java Cookbook 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.