v160 · multimedia · web audio

Worker direct line

The shared port is a MessagePort, so it can carry other ports. Create a MessageChannel, send one end to the audio global scope through audioWorklet.port and the other to a Worker: now the worker can synthesise heavy data — here an additive-synthesis wavetable — and transfer it straight to the audio thread. The main thread wires the line and then gets out of the way; it never sees a sample of the table.

Probing this browser…

main ──audioWorklet.port──▶ AudioWorkletGlobalScope └──Worker.postMessage──▶ Worker Worker ◀══ MessageChannel ══▶ AudioWorkletGlobalScope (not yet wired)

result
not run

the three pieces

// main: wire the line, then step aside
const { port1, port2 } = new MessageChannel();
ctx.audioWorklet.port.postMessage({ type: "attach-line", line: port2 }, [port2]);
worker.postMessage({ type: "line", line: port1 }, [port1]);

// worker: build + transfer straight to the audio thread
line.postMessage({ type: "wavetable", table }, [table.buffer]);

// AudioWorkletGlobalScope
port.onmessage = (e) => { if (e.data.type === "attach-line") e.data.line.onmessage = onTable; };

references