AudioWorkletGlobalScope

Baseline 广泛可用 *

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

* 此特性的某些部分可能存在不同级别的支持。

AudioWorkletGlobalScope 接口是 Web Audio API 的一部分,它代表了用户提供的代码的全局执行上下文,用于定义自定义的 AudioWorkletProcessor 派生类。

每个 BaseAudioContext 都有一个 AudioWorklet,可通过 audioWorklet 属性访问。该 AudioWorklet 在单个 AudioWorkletGlobalScope 中运行其代码。

由于全局执行上下文在当前 BaseAudioContext 中共享,因此可以在 worklet 中定义任何其他变量并执行任何允许的操作 — 除了定义 AudioWorkletProcessor 派生类。

WorkletGlobalScope AudioWorkletGlobalScope

实例属性

此接口还继承了其父接口 WorkletGlobalScope 中定义的属性。

currentFrame 只读

返回一个整数,表示正在处理的音频块的不断增加的当前样本帧。在处理完每个音频块后,它会增加 128(渲染量的大小)。

currentTime 只读

返回一个双精度浮点数,表示正在处理的音频块不断增加的上下文时间。它等于 worklet 所属的 BaseAudioContextcurrentTime 属性。

sampleRate 只读

返回一个浮点数,表示关联的 BaseAudioContext 的采样率。

port 只读 实验性

返回一个 MessagePort,用于主线程中的代码和 audio worklet 的全局作用域之间进行自定义、异步通信。这允许自定义消息,例如发送和接收控制数据或全局设置。

实例方法

此接口还继承了其父接口 WorkletGlobalScope 中定义的方法。

registerProcessor()

注册一个派生自 AudioWorkletProcessor 接口的类。然后可以通过创建 AudioWorkletNode 来使用该类,并提供其注册名称。

示例

在此示例中,我们在自定义 AudioWorkletProcessor 的构造函数中将所有全局属性输出到控制台。

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

js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);

接下来,在我们的主脚本文件中,我们将加载处理器,创建一个 AudioWorkletNode 实例 — 并将处理器的名称传递给它 — 然后将该节点连接到音频图。我们应该在控制台中看到 console.log() 调用的输出。

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

规范

规范
Web Audio API
# AudioWorkletGlobalScope

浏览器兼容性

另见