/**
 * AudioWorklet processor: 收集麦克风 PCM 采样数据
 * 运行在音频线程，通过 MessagePort 将 Float32Array 发回主线程
 */
class PCMRecorderProcessor extends AudioWorkletProcessor {
  constructor() {
    super()
    this._stopped = false
    this.port.onmessage = (e) => {
      if (e.data === 'stop') this._stopped = true
    }
  }

  process(inputs) {
    if (this._stopped) return false

    const input = inputs[0]
    if (input && input[0] && input[0].length > 0) {
      // 取第一个声道（mono），拷贝一份发给主线程
      this.port.postMessage(new Float32Array(input[0]))
    }
    return true
  }
}

registerProcessor('pcm-recorder-processor', PCMRecorderProcessor)
