AudioWorkletGlobalScope
Baseline 廣泛可用 *
AudioWorkletGlobalScope 介面是 Web Audio API 的一部分,它代表了使用者提供的程式碼的全域性執行上下文,用於定義自定義的 AudioWorkletProcessor 派生類。
每個 BaseAudioContext 都有一個 AudioWorklet,可透過 audioWorklet 屬性訪問。該 AudioWorklet 在單個 AudioWorkletGlobalScope 中執行其程式碼。
由於全域性執行上下文在當前 BaseAudioContext 中共享,因此可以在 worklet 中定義任何其他變數並執行任何允許的操作 — 除了定義 AudioWorkletProcessor 派生類。
例項屬性
此介面還繼承了其父介面 WorkletGlobalScope 中定義的屬性。
currentFrame只讀-
返回一個整數,表示正在處理的音訊塊的不斷增加的當前樣本幀。在處理完每個音訊塊後,它會增加 128(渲染量的大小)。
currentTime只讀-
返回一個雙精度浮點數,表示正在處理的音訊塊不斷增加的上下文時間。它等於 worklet 所屬的
BaseAudioContext的currentTime屬性。 sampleRate只讀-
返回一個浮點數,表示關聯的
BaseAudioContext的取樣率。 port只讀 實驗性-
返回一個
MessagePort,用於主執行緒中的程式碼和 audio worklet 的全域性作用域之間進行自定義、非同步通訊。這允許自定義訊息,例如傳送和接收控制資料或全域性設定。
例項方法
此介面還繼承了其父介面 WorkletGlobalScope 中定義的方法。
registerProcessor()-
註冊一個派生自
AudioWorkletProcessor介面的類。然後可以透過建立AudioWorkletNode來使用該類,並提供其註冊名稱。
示例
在此示例中,我們在自定義 AudioWorkletProcessor 的建構函式中將所有全域性屬性輸出到控制檯。
首先,我們需要定義處理器並註冊它。請注意,這應該在單獨的檔案中完成。
// 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() 呼叫的輸出。
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 |
瀏覽器相容性
載入中…