Java Audio : Playing PCM amplitude Array

How to play a array of PCM amplitude values (integer or float array) in Java - Steps

Basic Steps :
//initialize source data line - for playback
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
line.start();

//play the byteArray
line.write(byteArray, 0,  byteArray .length);//(byte[] b, int off, int len)
line.drain();
line.close();

Converting integer array to bytearray :
We need to convert our PCM array to byteArray because the line.write requires byte[] b as parameter.

  byte b = (byte)(i*127f);

Full code : This example plays the randomly generated array :

public class PlayAnArray {
    private static int sampleRate = 16000;
    public static void main(String[] args) {
        try {
            final AudioFormat audioFormat = new AudioFormat(sampleRate, 8, 1, true, true);
            SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat );
            line.open(audioFormat );
            line.start();
            for (int i = 0; i < 5; i++) {//repeat in loop
                play(line, generateRandomArray());
            }
            line.drain();
            line.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static byte[] generateRandomArray() {
        int size = 20000;
        System.out.println(size);
        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) {
        int length = sampleRate * array.length / 1000;
        line.write(array, 0, array.length);
    }
}


You may modify generateRandomArray to play different waveforms like SINE wave, square wave... etc

For playing a wave file in java follow my post on How to play wave file on java

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...