|
Java's audio support comes from the AppletContext class and the AudioClip interface.
Since applications don't have applet contexts, they have no easy way to play audio clips.
This is supposed to be fixed in Java 1.2. In the meantime you have to use undocumented
classes in the sun packages. The following example demonstrates:
import sun.audio.*; import java.awt.*; import java.io.*;
public class SoundPlayer extends Frame implements FilenameFilter {
Button openButton = new Button("Open"); Button playButton = new Button("Play"); Button loopButton = new Button("Loop"); Button stopButton = new Button("Stop"); Label filename = new Label(" "); File theFile = null; AudioData theData = null; InputStream nowPlaying = null;
public SoundPlayer() { super("Sound Player"); resize(300, 200); Panel north = new Panel(); north.setLayout(new FlowLayout(FlowLayout.LEFT)); north.add(new Label("File: ")); north.add("North", filename); add("North", north); Panel south = new Panel(); south.add(openButton); south.add(playButton); south.add(loopButton); south.add(stopButton); add("South", south); }
public static void main(String[] args) { SoundPlayer sp = new SoundPlayer(); sp.show(); }
public void open() { FileDialog fd = new FileDialog(this, "Please select a .au file:"); fd.setFilenameFilter(this); fd.show(); try { theFile = new File(fd.getDirectory() + "/" + fd.getFile()); if (theFile != null) { filename.setText(theFile.getName()); FileInputStream fis = new FileInputStream(theFile); AudioStream as = new AudioStream(fis); theData = as.getData(); } } catch (IOException e) { System.err.println(e); } }
public void play() { stop(); if (theData == null) open(); if (theData != null) { AudioDataStream ads = new AudioDataStream(theData); AudioPlayer.player.start(ads); nowPlaying = ads; } }
public void stop() { if (nowPlaying != null) { AudioPlayer.player.stop(nowPlaying); nowPlaying = null; } }
public void loop() { stop(); if (theData == null) open(); if (theData != null) { ContinuousAudioDataStream cads = new ContinuousAudioDataStream(theData); AudioPlayer.player.start(cads); nowPlaying = cads; } }
public boolean action(Event e, Object what) {
if (e.target == playButton) { play(); return true; } else if (e.target == openButton) { open(); return true; } else if (e.target == loopButton) { loop(); return true; } else if (e.target == stopButton) { stop(); return true; }
return false;
}
public boolean accept(File dir, String name) {
name = name.toLowerCase(); if (name.endsWith(".au")) return true; if (name.endsWith(".wav")) return true; return false;
}
}
This example is taken from Chapter 10 of Java
Secrets,
available from amazon
(Java Secrets)
and various independent bookstores. It's published by IDG Books, ISBN
number 0-764-58007-8. Chapters 8-17 cover various of the sun packages
including sun.audio. (Chapters 1-7 cover the internals of Java like byte
code and class files. Chapter 19 and 20 cover platform dependent Java
including native methods.) |