音频流并获取振幅以同时绘制波形

时间:2018-09-29 16:47:30

标签: android audio-streaming visualizer

我正在尝试流式传输并获取振幅以绘制波形。当我流式传输并注释代码以获取振幅时,它的工作正常。我想问题是音频记录.read()由流以及振幅方法分别调用。一旦在read()方法中调用它,然后在getAmplitude()方法中调用它。我正在寻找一种使流和幅值协同工作的方法。使用现有代码,流媒体跳过。下面是代码:

public void start() {
  if (isCreated()) {
    init();
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (running && !Thread.interrupted()) {
          DataTaken dataTaken = read();
          if (dataTaken != null) {
            Log.e("amplitude ",getAmplitude()+"");
            amplitude = getAmplitude();
            getMicrophoneData.inputPCMData(dataTaken.getPcmBuffer(), dataTaken.getSize());
          } else {
            running = false;
          }
        }
      }
    }).start();
  } else {
    Log.e(TAG, "Microphone no created, MicrophoneManager not enabled");
  }
} 

  private DataTaken read() {
    int size;
    if (muted) {
      size = audioRecord.read(pcmBufferMuted, 0, pcmBufferMuted.length);
    } else {
      size = audioRecord.read(pcmBuffer, 0, pcmBuffer.length);
    }
    if (size <= 0) {
      return null;
    }
    return new DataTaken(pcmBuffer, size);
}

public double getAmplitude() {
  if(audioRecord != null) {
    short[] buffer = new short[getPcmBufferSize()];
    audioRecord.read(buffer, 0, getPcmBufferSize());
    int max = 0;
    for (short s : buffer) {
      if (Math.abs(s) > max) {
        max = Math.abs(s);
      }
    }
    return max;
  }else{
    return 0;
  }
}

public class DataTaken {

  private byte[] pcmBuffer;
  private int size;

  public DataTaken(byte[] pcmBuffer, int size) {
    this.pcmBuffer = pcmBuffer;
    this.size = size;
  }

  public byte[] getPcmBuffer() {
    return pcmBuffer;
  }

  public void setPcmBuffer(byte[] pcmBuffer) {
    this.pcmBuffer = pcmBuffer;
  }

  public int getSize() {
    return size;
  }

  public void setSize(int size) {
    this.size = size;
  }
}

1 个答案:

答案 0 :(得分:0)

问题是您两次致电AudioRecord.read()

DataTaken dataTaken = read();

您正在将pcmBuffer存储在DataTaken中。因此,在调用buffer时使用相同的getAmplitude()

getAmplitude(dataTaken.getPcmBuffer());

您的getAmplitude()方法如下:

public double getAmplitude(short[] buffer){

    int max = 0;
    for (short s : buffer) {
      if (Math.abs(s) > max) {
        max = Math.abs(s);
      }
    }
    return max;
  }else{
    return 0;
  }
}

此外,为什么还要两次致电getAmplitude()?像这样更改它:

amplitude = getAmplitude();
Log.e("amplitude ",amplitude+"");

这种方式更有效。