class AudioProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.desiredBufferSize = 20*1024; // 期望的缓冲区大小
    this.buffer = new Float32Array(this.desiredBufferSize);
    this.bufferIndex = 0;
  }

  process(inputs, outputs, parameters) {
    const input = inputs[0];
    const channel = input[0];
    
    if (channel && channel.length > 0) {
      // 将新数据添加到缓冲区
      for (let i = 0; i < channel.length; i++) {
        this.buffer[this.bufferIndex++] = channel[i];
        
        // 当缓冲区满时，发送数据
        if (this.bufferIndex >= this.desiredBufferSize) {
          // 将浮点音频数据转换为16位整数
          const pcmData = new Int16Array(this.desiredBufferSize);
          for (let j = 0; j < this.desiredBufferSize; j++) {
            pcmData[j] = Math.min(Math.max(this.buffer[j] * 32767, -32767), 32767);
          }
          
          // 发送数据到主线程
          this.port.postMessage(pcmData.buffer, [pcmData.buffer]);
          
          // 重置缓冲区
          this.buffer = new Float32Array(this.desiredBufferSize);
          this.bufferIndex = 0;
        }
      }
    }
    
    return true;
  }
}

registerProcessor('audio-processor', AudioProcessor); 