svelte-audio-renderer

Audio worklets

<audioWorklet> creates an AudioWorkletNode for a processor you registered.

Write a processor

The processor runs on the audio thread, in a module of its own.

static/noise-processor.js
class NoiseProcessor extends AudioWorkletProcessor {
	static get parameterDescriptors() {
		return [{ name: 'amount', defaultValue: 1, minValue: 0, maxValue: 1 }];
	}

	process(_inputs, outputs, parameters) {
		const amount = parameters.amount;
		for (const channel of outputs[0]) {
			for (let i = 0; i < channel.length; i++) {
				channel[i] = (Math.random() * 2 - 1) * (amount[i] ?? amount[0]);
			}
		}
		return true;
	}
}

registerProcessor('noise', NoiseProcessor);

Load it, then render the node

Load the module with audioWorklet.addModule() before the element renders, then use the name you passed to registerProcessor().

<script lang="ts">
	import { getAudioContext } from 'svelte-audio-renderer';

	const loading = getAudioContext().audioWorklet.addModule('/noise-processor.js');
</script>

{#await loading then}
	<gain gain={0.1}>
		<audioWorklet name="noise" numberOfInputs={0} amount={0.5}></audioWorklet>
	</gain>
{/await}

Attributes

  • name is the processor's name. It is required.
  • Custom AudioParams from parameterDescriptors, such as amount, work like built-in ones.
  • numberOfInputs, numberOfOutputs, outputChannelCount, parameterData and processorOptions are creation options.

The Noise worklet example runs this processor.