Playing a Sound File

The following code provides an example of one way to play a sound file using Java. You can download the related image and sound file here:

Image:


Sound File:
hal.wav


Important: If you are working with OS X on a Mac, make sure you have downloaded, installed, and made eclipse aware of a JDK that is as new or newer than 1.8 (update 66).

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.sound.sampled.*;
import javax.swing.*;

import acm.graphics.GImage;
import acm.graphics.GLabel;
import acm.program.GraphicsProgram;
   
public class JavaAudioPlaySoundExample extends GraphicsProgram {
    
    private final String pathToClip = "/Users/pauloser/Desktop/hal.wav";
    private final String pathToImage = "/Users/pauloser/Desktop/hal.jpg";
    private final Color backgroundColor = new Color(50,50,50);
    private JButton playBtn;
    private boolean soundLoaded;
    private Clip clip;
   
    public void init() {
      // set background to a dark gray
      this.setSize(230,300);
      this.getGCanvas().setBackground(backgroundColor);
      
      // put an image and label of the HAL 9000 computer on the canvas
      GImage halImage = new GImage(pathToImage);
      halImage.setLocation(11,40);
      this.add(halImage);
      GLabel halLabel = new GLabel("HAL 9000");
      halLabel.setColor(Color.WHITE);
      halLabel.setLocation(85,25);
      this.add(halLabel);
      
      // try to load the sound from the file...
      try {
         // Open an audio input stream.
         File file = new File(pathToClip);
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
         
         // Get a sound clip resource, open audio clip, and 
         // load samples from the audio input stream.
         clip = AudioSystem.getClip();
         clip.open(audioIn);
         soundLoaded = true;
      } 
      catch (UnsupportedAudioFileException e) {
         soundLoaded = false; 
         e.printStackTrace();
      } 
      catch (IOException e) {
         soundLoaded = false; 
         e.printStackTrace();
      } 
      catch (LineUnavailableException e) {
         soundLoaded = false; 
         e.printStackTrace();
      }

      // make a button to play sound clip...
      playBtn = new JButton("Open Pod Bay Doors");
      playBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (soundLoaded) {
                    	if (clip.isRunning())
                            clip.stop();   // Stop the player if it is still running
                        clip.setFramePosition(0); // rewind to the beginning
                        clip.start();     // Start playing   			
                }
            }});
      this.getRegionPanel(SOUTH).add(playBtn);
   }
}

More information on how to integrate sound into a java program can be found here