zoukankan      html  css  js  c++  java
  • Java Audio : Playing PCM amplitude Array

    转载自: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

  • 相关阅读:
    d3 之deal with data
    git 使用小结
    【nodemailer】之 work with mustache
    Mustache
    【nodemailer】 初试
    【计算机基础】二.组成1(总线、输入输出)
    【计算机基础】一.概述
    Sring事务管理
    【并发编程】4.JUC中常用的锁
    【并发编程】3.线程与线程池
  • 原文地址:https://www.cnblogs.com/passedbylove/p/11888709.html
Copyright © 2011-2022 走看看