This snippet shows how to play .wav or .au file. The following steps need to be done.
- Get the AudioInputStream for the audio file
- Check the PCM_SIGNED encoding, else convert
- Create the AudioClip using the DataLine object
- Finally play the clip and close stream and clip when done.
package com.livrona.snippets.audio;
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;
/**
* This snippet show how to play any music file in in either .wav or .au
* format.
*
* @author mvohra
*
*/
publicclass MusicPlayer {
private AudioInputStream stream =null;
private Clip clip =null;
/**
* Stop Playing the cleanup resources
*/
publicvoid stopPlaying() {
clip.stop();
clip.close();
try {
stream.close();
} catch (IOException e) {
System.out.println("Failed to close the stream "+ e.getMessage());
e.printStackTrace();
}
}
/**
* Start Playing the music file
*
* @param fileName
*/
publicvoid startPlaying(String fileName) {
try {
// From file
stream = AudioSystem.getAudioInputStream(new File(fileName));
// At present, ALAW and ULAW encodings must be converted
// to PCM_SIGNED before it can be played
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format =new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2, format.getChannels(),
format.getFrameSize() * 2, format.getFrameRate(), true); // big
// endian
stream = AudioSystem.getAudioInputStream(format, stream);
}
// Create the clip
DataLine.Info info =new DataLine.Info(Clip.class, stream
.getFormat(), ((int) stream.getFrameLength() * format
.getFrameSize()));
clip = (Clip) AudioSystem.getLine(info);
// This method does not return until the audio file is completely
// loaded
clip.open(stream);
// Start playing
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* App Launcher , main(..) method
*
* @param args
*/
publicstaticvoid main(String[] args) throws Exception {
if (args.length !=1) {
System.out
.println("Usage: java com.livrona.snippets.audio.MidiPlayer <Path of your sound clip, in either .wav or au>");
System.exit(0);
}
String musicFile = args[0];
System.out.println("File : "+ musicFile);
// create the player
MusicPlayer player =new MusicPlayer();
// start
player.startPlaying(musicFile);
System.out.println("Music file is playing..");
// play for say 10 secs and then stop
Thread.sleep(10000);
System.out.println("About to stop the music ..");
// stop
player.stopPlaying();
}
}