svelte-audio-renderer

Direct node access

Anything that isn't a value, such as automation, reading an analyser or setPeriodicWave, uses the real node.

audioNode

audioNode makes an attachment for {@attach}. Its callback receives the element's AudioNode once it exists.

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

	const pluck = audioNode((gain: GainNode) => {
		const now = gain.context.currentTime;
		gain.gain.setValueAtTime(1, now);
		gain.gain.setTargetAtTime(0, now, 0.1);
	});
</script>

<gain {@attach pluck}>
	<oscillator type="triangle" frequency={330}></oscillator>
</gain>

Cleanup

A function returned from the callback runs when the element is removed.

const watch = audioNode((analyser: AnalyserNode) => {
	const samples = new Float32Array(analyser.fftSize);
	let frame = requestAnimationFrame(function read() {
		analyser.getFloatTimeDomainData(samples);
		frame = requestAnimationFrame(read);
	});
	return () => cancelAnimationFrame(frame);
});

The AudioContext

getAudioContext() returns the context in any component under setAudioContext, for example to read currentTime or to decode audio data.

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

	const context = getAudioContext();
</script>