svelte-audio-renderer

Getting started

Install the package, turn on custom renderers and play a sound.

Install

It requires svelte@^5.59.

pnpm add svelte-audio-renderer
# or
bun add svelte-audio-renderer

Turn on custom renderers

Custom renderers are behind an experimental flag in the Svelte compiler options.

svelte.config.js
export default {
	compilerOptions: {
		experimental: { customRenderer: true }
	}
};

Write an audio component

An audio component opts in to the renderer with <svelte:options>. Its markup is the audio graph: children connect to their parent, and the top-level nodes connect to the context's destination.

Synth.svelte
<svelte:options customRenderer="svelte-audio-renderer" />

<script lang="ts">
	interface Props {
		frequency?: number;
		cutoff?: number;
	}

	let { frequency = 220, cutoff = 800 }: Props = $props();
</script>

<gain gain={0.2}>
	<biquadFilter type="lowpass" frequency={cutoff} Q={4}>
		<oscillator type="sawtooth" {frequency}></oscillator>
	</biquadFilter>
</gain>

Use it in a page

A normal page provides the AudioContext with setAudioContext, then renders audio components like any other component.

+page.svelte
<script lang="ts">
	import { setAudioContext } from 'svelte-audio-renderer';
	import Synth from './Synth.svelte';

	let context: AudioContext | undefined;
	let playing = $state(false);
	let cutoff = $state(800);

	setAudioContext(() => (context ??= new AudioContext()));

	function toggle() {
		context ??= new AudioContext();
		void context.resume();
		playing = !playing;
	}
</script>

<button onclick={toggle}>{playing ? 'Stop' : 'Play'}</button>
<input type="range" min="200" max="4000" bind:value={cutoff} />

{#if playing}
	<Synth {cutoff} />
{/if}

Browsers start audio suspended

A new AudioContext stays suspended until the user interacts with the page. Call resume() from a click or key press, as toggle does above.

Server-side rendering

setAudioContext takes a function, and the first audio component calls it. Audio components render nothing during SSR, so AudioContext, which does not exist on the server, is never created there. You don't need ssr = false.

Next

Read how elements and attributes map to Web Audio, or open the examples.