Working with Audio

So you’ve read all the material on drawing and image processing, and you’re wondering what in the world audio has to do with images. Well, not much, actually, except that true multimedia presentations often combine image techniques such as animation with sound. So we’re going to spend a few minutes here talking about audio, for lack of a better place to discuss it.

The Java Sound API is a new core API in SDK 1.3. It provides fine-grained support for the creation and manipulation of both sampled audio and MIDI music. There’s space here only to scratch the surface by examining how to play sampled sound and MIDI music files.

java.applet.AudioClip defines an interface for objects that can play sound. An object that implements AudioClip can be told to play( ) its sound data, stop( ) playing the sound, or loop( ) continually.

The Applet class provides a handy static method, newAudioClip( ) , that retrieves sounds from files or over the network. This method takes an absolute or relative URL to specify where the audio file is located. The following application, NoisyButton, gives a simple example:

//file: NoisyButton.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class NoisyButton extends JFrame {

  public NoisyButton(final AudioClip sound) {
    // set up the frame
    setTitle("NoisyButton");
    addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    setSize(200, 200);
    setLocation(100, 100);
    // set up the button
    JButton button = new JButton("Woof!");
    button.addActionListener(new ActionListener( ) {
      public void actionPerformed(ActionEvent e) { sound.play( ); }
    });
    getContentPane( ).setBackground(Color.pink);
    getContentPane().setLayout(new GridBagLayout( ));
    getContentPane( ).add(button);
    setVisible(true);
  }

  public static void main(String[] args) throws Exception {
    java.io.File file = new java.io.File("bark.aiff");
    AudioClip sound = Applet.newAudioClip(file.toURL( ));
    new NoisyButton(sound);
  }
}

NoisyButton retrieves an AudioClip from the file bark.aiff ; we use File to represent the file and toURL( ) to create a URL that represents the file. (You might want to use a command-line argument to specify the file name instead.) When the button is pushed, we call the play( ) method of the AudioClip to start things. After that, it will play to completion unless we call the stop( ) method to interrupt it.

Playback is the limit of Java 2’s built-in sound capabilities. However, you can play back a wide range of file formats: AIFF, AU, Windows WAV, standard MIDI files, and Rich Music Format (RMF) files. For a little extra zing in your applications, consider adding sound.

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