Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata