Basic Steps:
// Initialize a SourceDataLine for playback
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
line.start();
// Write the entire byte array to the line
line.write(byteArray, 0, byteArray.length);
line.drain();
line.close();
Converting integer or float arrays to a byte array:
The line.write() method expects a byte[], so your raw PCM amplitude values must be packed accordingly. The conversion depends on the audio format you choose. For 8‑bit signed PCM (what we’ll use in the example), a normalised float between -1 and 1 maps to a single byte with
(byte)(amplitude * 127). For 16‑bit signed, you’d need to write two bytes per sample in the correct endian order. The snippet below shows the simple 8‑bit mapping.
// Convert a normalised float ([-1,1]) to an 8-bit signed byte
byte b = (byte)(i*127f);
Full Working Example: Play Random Noise
public class PlayAnArray {
private static int sampleRate = 16000;
public static void main(String[] args) {
try {
// Audio format: 16 kHz, 8-bit, mono, signed, big-endian
final AudioFormat audioFormat = new AudioFormat(sampleRate, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
line.start();
// Play 5 bursts of random noise
for (int i = 0; i < 5; i++) {
play(line, generateRandomArray());
}
line.drain();
line.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] generateRandomArray() {
int size = 20000; // number of samples
byte[] byteArray = new byte[size];
for (int i = 0; i < size; i++) {
byteArray[i] = (byte) (Math.random() * 127f);
}
return byteArray;
}
private static void play(SourceDataLine line, byte[] array) {
// Optional: calculate duration (ms) = length of array / (sampleRate / 1000)
// int length = sampleRate * array.length / 1000; // not used here
line.write(array, 0, array.length);
}
}
Modify
generateRandomArray() to produce sine waves, square waves, or any other waveform—just fill the byte array with your desired samples.For playing WAV files in Java, see my post on How to Play a WAV File in Java.
No comments :
Post a Comment
Your Comment and Question will help to make this blog better...