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

瀏覽器相容性

另見