WebAudio API:如何访问 AudioWorkletProcessor 中的时间/采样率?

WebAudio API: How to access time / sample rate in a AudioWorkletProcessor?

我想实现一个了解时间的 AudioWorkletProcessor。例如:如何将DelayNode重新实现为Processor?

MDN 文档说:

By specification, each block of audio your process() function receives contains 128 frames (that is, 128 samples for each channel), but it is planned that this value will change in the future, and may in fact vary depending on circumstances, so you should always check the array's length rather than assuming a particular size.

我可以用输入的长度得到帧数,但是如何得到使用的采样率?这样我就可以知道这个输入有多长(以秒为单位)。

我的最终目标是能够计算特定时间内信号的平均能量 window。

class EnergyProcessor extends AudioWorkletProcessor {
  process(inputs, outputs, parameters) {
    if (inputs.length !== 1) {
      throw 'invalid inputs'
    }

    // how much time is covered by inputs?

    inputs[0].forEach((channel, channelID) => {
      let sum = 0
      let count = 0

      channel.forEach((value, i) => {
        sum += value * value
        count += 1

        for (let o = 0; o < outputs.length; o++) {
          // skip when writing x channels to x - 1
          if (channelID >= outputs[o].length) {
            continue
          }
          outputs[o][channelID][i] = sum / count
        }
      })
    })

    return true
  }
}

registerProcessor('EnergyProcessor', EnergyProcessor)

The MDN says那个

[...] lives in the AudioWorkletGlobalScope and runs on the Web Audio rendering thread.

据说

AudioWorkletGlobalScope 引用了其上下文的

sampleRate: Read only
Returns a float that represents the sample rate of the associated BaseAudioContext.

所以你可能可以简单地、神奇地

console.log(sampleRate)

或您需要做的任何事情。