AudioPlayerExample1.java

This is an example program that demonstrates how to play back an audio file using the Clip in Java Sound API.

C:\ece538\audio>java AudioPlayerExample1
PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian
Playback started.
Playback completed.
ellapsed time 1 seconds

Generally, the Java Sound API (package: javax.sound) provides two ways for playing back audio: using a Clip and using a SourceDataLine. Each way has its own advantages and drawbacks.

Use a Clip (javax.sound.sampled.Clip) when you want to play non-real-time sound data such as a short sound file. The whole file is pre-loaded into memory before playing back, therefore we have total control over the playback.

Advantages

Reference: Java audio from www.codejava.net


AudioPlayerExample1.java

import java.io.File;
import java.io.IOException;
 
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
 
/**
 * This is an example program that demonstrates how to play back an audio file
 * using the Clip in Java Sound API.
 * @author www.codejava.net
 *
 */
public class AudioPlayerExample1 implements LineListener {
     
    /**
     * this flag indicates whether the playback completes or not.
     */
    boolean playCompleted;
     
    /**
     * Play a given audio file.
     * @param audioFilePath Path of the audio file.
     */
    void play(String audioFilePath) {
        File audioFile = new File(audioFilePath);
 
        try {
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
 
            AudioFormat format = audioStream.getFormat();
	    System.out.println(format);		
 
            DataLine.Info info = new DataLine.Info(Clip.class, format);
 
            Clip audioClip = null;
	    try {
		audioClip = (Clip) AudioSystem.getLine(info);
 	    }
	    catch(Exception ex) {
		System.err.println("Audio format not supported");
		System.exit(-1);
	    }
	
 
            audioClip.open(audioStream);

            audioClip.addLineListener(this);

             
            audioClip.start();
            int count=0; 
            while (!playCompleted) {
                // wait for the playback completes
                try {
                    Thread.sleep(1000);
		    count++;
                } catch (InterruptedException ex) {
                    System.err.println(ex.getMessage());
                }
            }
	    System.out.println("ellapsed time " + count + " seconds");
             
            audioClip.close();
             
        } catch (UnsupportedAudioFileException ex) {
            System.out.println("The specified audio file is not supported.");
            //ex.printStackTrace();
        } catch (LineUnavailableException ex) {
            System.out.println("Audio line for playing back is unavailable.");
            //ex.printStackTrace();
        } catch (IOException ex) {
            System.err.println("Error playing the audio file.");
            //ex.printStackTrace();
        }
         
    }
     
    /**
     * Listens to the START and STOP events of the audio line.
     */
    @Override
    public void update(LineEvent event) {
        LineEvent.Type type = event.getType();
         
        if (type == LineEvent.Type.START) {
            System.out.println("Playback started.");
             
        } else if (type == LineEvent.Type.STOP) {
            playCompleted = true;
            System.out.println("Playback completed.");
        }
 
    }
 
    public static void main(String[] args) {
        String audioFilePath = args.length>0? args[0]: "cuckoo.wav";
        AudioPlayerExample1 player = new AudioPlayerExample1();
        player.play(audioFilePath);
    }
 
}


Maintained by John Loomis, updated Thu May 07 15:32:27 2020