简体   繁体   English

使用TargetDataLine来获取实时音频:缓冲区不变

[英]Using TargetDataLine to get real-time audio: buffer does not change

I have some code like this: 我有一些这样的代码:

  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);
    }
  }

I have a tempBuffer, in which I store 10000 bytes at a time. 我有一个tempBuffer,我一次存储10000个字节。 Each time I have 10000 bytes worth of audio, I send it along a request thread to process this chunk of audio. 每当我有10000个字节的音频时,我都会通过请求线程将其发送以处理该音频块。 My problem is that I keep sending the same buffer with the same audio to every single one of my request threads. 我的问题是,我不断向每个请求线程中的每个发送相同缓冲区的音频。

In my mind, what is supposed to happen is that targetDataLine will read the audio 10000 bytes at a time and pass each of tempBuffers containing different parts of my audio to each of my request threads. 在我看来,应该发生的是targetDataLine一次读取音频10000个字节,并将包含音频不同部分的每个tempBuffers传递给每个请求线程。

Perhaps I have misunderstood TargetDataLine. 也许我误解了TargetDataLine。

You are only creating tempBuffer once, outside of your loop. 您只需在循环外创建一次tempBuffer Each call to targetDataLine.read is overwriting the contents of the buffer with the new data. 每次对targetDataLine.read调用targetDataLine.read用新数据覆盖缓冲区的内容。 Unless you are copying the buffer in the RequestThread constructor this will cause problems. 除非您在RequestThread构造函数中复制缓冲区,否则将导致问题。 You should proably create a new buffer for each read: 您应该为每次读取创建一个新的缓冲区:

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

You must also take notice of the number of bytes read returned by the read (your cnt variable). 您还必须注意读取(您的cnt变量)返回的读取字节数。 The read does not guarantee to fill the buffer. 读取并不能保证填充缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM