![]() |
AudioInputStream class.
AudioFormat object from the stream.
DataLine.Info object from the format.
SourceDataLine object.
AudioInputStream class.AudioSystem.getAudioInputStream(String
fileName) and create an AudioInputStream object.
The size of the buffer will be set to the byte size of the file,
obtained by available() method. Read the sound file and
save the data to a buffer.
AudioInputStream stream=AudioSystem.getAudioInputStream(file); byte buf=new byte[stream.available()]; stream.read(buf,0,buf.length);
AudioFormat object from the stream.AudioFormat can be obtained from the stream by
stream.getFormat() method. nBytesRead is
set to the byte size of the data.
AudioFormat format=stream.getFormat(); long nBytesRead=format.getFrameSize()*stream.getFrameLength();
DataLine.Info object from the format.DataLine.Info class from the format obtained from step. 2.
DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);
SourceDataLine object by calling the static AudioSystem.getLine(DataLine.Info) method.
SourceDataLine line=(SourceDataLine)AudioSystem.getLine(info);
Now the line is ready to play the sound file. Prior to writing the data
to the line, open and start the line.
line.open(format); line.start();
Write the data to play using write(byte[] buffer,int start, int
length).
line.write(buf,0,(int)nBytesRead);
Make sure to drain and close the line.
line.drain(); line.close();
playWavFile(String fileName) method takes the sound file
name as an argument and read and play the file. Click here to
download a test class PlayWavFile.java
that uses this method and a test sound file emma.wav in WAVE format.
import javax.sound.sampled.*;
import java.io.*;
public void playWavFile(String fileName)
{
try
{
File file=new File(fileName);
if(file.exists())
{
// Read the sound file using AudioInputStream.
AudioInputStream stream=AudioSystem.getAudioInputStream(file);
byte[] buf=new byte[stream.available()];
stream.read(buf,0,buf.length);
// Get an AudioFormat object from the stream.
AudioFormat format=stream.getFormat();
long nBytesRead=format.getFrameSize()*stream.getFrameLength();
// Construct a DataLine.Info object from the format.
DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);
SourceDataLine line=(SourceDataLine)AudioSystem.getLine(info);
// Open and start the line.
line.open(format);
line.start();
// Write the data out to the line.
line.write(buf,0,(int)nBytesRead);
// Drain and close the line.
line.drain();
line.close();
}
}catch(Exception e){e.printStackTrace();}
}
|
| A sample code that plays a given sound file. |
Please refer to the following site for more information on Java Sound API.
AudioClip class is a another simpler format to play sound files.
AudioClip, though, will not give you the freedom to start
and stop the sound file in any way as SourceDataLine does.
Please refer to the following site for more information on
AudioClip.