AudioWorkletNode: parameters 属性

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

AudioWorkletNode 接口中只读的 parameters 属性返回关联的 AudioParamMap,即一个类似 MapAudioParam 对象集合。它们是在创建底层 AudioWorkletProcessor 时根据其 parameterDescriptors 静态 getter 实例化的。

包含 AudioParam 实例的 AudioParamMap 对象。它们可以像默认 AudioNode 一样进行自动化,并且其计算值可以在你的 AudioWorkletProcessorprocess 方法中使用。

示例

为了演示自定义 AudioParam 的创建和使用,我们将扩展 AudioWorkletNode 页面的示例。在那里,我们创建了一个输出白噪声的简单节点。在这里,我们额外创建一个自定义增益参数,以便我们可以直接更改输出音量(尽管你也可以使用 GainNode 来实现这一点)。

首先,我们需要定义一个自定义 AudioWorkletProcessor 并注册它。请注意,这应该在一个单独的文件中完成。

我们通过添加一个静态 parameterDescriptors getter 来扩展处理器。它将由 AudioWorkletNode 构造函数在内部使用,以使用实例化的 AudioParam 对象填充其 parameters

js
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
  static get parameterDescriptors() {
    return [
      {
        name: "customGain",
        defaultValue: 1,
        minValue: 0,
        maxValue: 1,
        automationRate: "a-rate",
      },
    ];
  }

  process(inputs, outputs, parameters) {
    const output = outputs[0];
    output.forEach((channel) => {
      for (let i = 0; i < channel.length; i++) {
        channel[i] =
          (Math.random() * 2 - 1) *
          (parameters["customGain"].length > 1
            ? parameters["customGain"][i]
            : parameters["customGain"][0]);
        // note: a parameter contains an array of 128 values (one value for each of 128 samples),
        // however it may contain a single value which is to be used for all 128 samples
        // if no automation is scheduled for the moment.
      }
    });
    return true;
  }
}

registerProcessor("white-noise-processor", WhiteNoiseProcessor);

接下来,在我们的主脚本文件中,我们将加载处理器,创建一个 AudioWorkletNode 实例,并传入处理器的名称,然后将该节点连接到音频图。

js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("white-noise-processor.js");
const whiteNoiseNode = new AudioWorkletNode(
  audioContext,
  "white-noise-processor",
);
whiteNoiseNode.connect(audioContext.destination);

现在我们可以这样更改节点的增益

js
const gainParam = whiteNoiseNode.parameters.get("customGain");
gainParam.setValueAtTime(0, audioContext.currentTime);
gainParam.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.5);

规范

规范
Web Audio API
# dom-audioworkletnode-parameters

浏览器兼容性

另见