转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-audio-playing-pcm-amplitude-array.html

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

posted on 2019-11-19 13:28  你不知道的浪漫  阅读(185)  评论(0编辑  收藏  举报