我有一些这样的代码:

  byte tempBuffer[] = new byte[10000];

  //call sleep thread (how long specified by second parameter)
  //After sleep time is up it sets stopCapture to true
  AudioSleepThread ast = new AudioSleepThread(this, seconds);
  ast.start();

  while(!this.stopCapture) {
    //this method blocks
    int cnt = targetDataLine.read(tempBuffer, 0, tempBuffer.length);
    System.out.println(cnt);
    if (cnt>0) {
          // Subsequent requests must **only** contain the audio data.
          RequestThread reqt = new RequestThread(responseObserver, requestObserver, tempBuffer);
          reqt.start();
          //Add it to array list
          this.reqtArray.add(reqt);
    }
  }

我有一个tempBuffer,其中一次存储10000个字节。每当我有10000个字节的音频时,我就会通过请求线程将其发送以处理该音频块。我的问题是我不断向每个请求线程中的每个发送相同缓冲区的音频。

在我看来,应该发生的是targetDataLine一次读取音频10000个字节,并将包含音频不同部分的每个tempBuffers传递给每个请求线程。

也许我误解了TargetDataLine。

最佳答案

您只需在循环外创建一次tempBuffer。每次对targetDataLine.read的调用都会用新数据覆盖缓冲区的内容。除非您在RequestThread构造函数中复制缓冲区,否则将导致问题。您应该为每次读取创建一个新的缓冲区:

while(!this.stopCapture) {
  byte tempBuffer[] = new byte[10000];
  //this method blocks
  int cnt = targetDataLine.read(tempBuffer, 0, tempBuffer.length);

您还必须注意读取(您的cnt变量)返回的读取字节数。读取并不能保证填充缓冲区。

10-08 09:22