The following simple application demonstrates how to play back a WAV audio file with Java APIs.
The key step is to specify the correct parameters and create an AudioFormat object.
package com.stackoverflow.AudoPlayback;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class AudioPlayback {
private SourceDataLine dataLine;
private AudioFormat audioFormat;
public AudioPlayback() throws LineUnavailableException {
audioFormat = new AudioFormat(Encoding.PCM_UNSIGNED, // Encoding
11025, // Sample Rate
8, // Sample Size in Bits
1, // Channels
1, // Frame Size
8000, // Frame Rate
false); // Little Endian
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat, 1000);
dataLine = (SourceDataLine) AudioSystem.getLine(info);
}
public void start() throws LineUnavailableException {
dataLine.open(audioFormat);
dataLine.start();
}
public void stop() {
dataLine.stop();
dataLine.close();
}
public void play(byte[] buffer, int offset, int length) {
dataLine.write(buffer, offset, length);
dataLine.drain();
}
public static void main(String[] args) {
try {
File audioFile = new File("audio.wav");
DataInputStream input = new DataInputStream(new BufferedInputStream(
new FileInputStream(audioFile)));
AudioPlayback playBack = new AudioPlayback();
byte[] data = new byte[64 * 1024]; // 65 KB buffer
int length = 0;
int playbackLength = 0;
long totalLength = audioFile.length();
playBack.start();
do {
length = input.read(data);
playBack.play(data, 0, length);
playbackLength += length;
} while (playbackLength < totalLength);
playBack.stop();
input.close();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment