useSound
Low-latency playback of short sounds decoded into memory.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-sound.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-sound.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-sound.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-sound.jsonUsage
<script lang="ts">
import { Button } from "#lib/components/ui/button/index.js";
import { useSound } from "#lib/hooks/use-sound.svelte.js";
const ding = useSound("/sounds/ding.mp3", { volume: 0.8 });
</script>
<Button onclick={ding.play}>Ding</Button>The sound is fetched and decoded once per page, then plays instantly on every trigger. src can also be an AudioBuffer you made yourself.
Call it during component setup. src and the options can be getters, such as () => sound.src and () => ({ volume }). isPlaying, isLoaded, duration and error are getters, so read them from the returned object.
Routing
By default a sound plays through the speakers. Pass destination: null and route output yourself, for example into a mixer channel:
const pad = useSound(src, { destination: null });
useWebAudioMixer(mixer, { inputs: { sounds: pad.output } });Options
| Prop | Type | Default |
|---|---|---|
volume 0..1 gain. | number | 1 |
playbackRate | number | 1 |
loop | boolean | false |
interrupt Restart instead of layering. | boolean | true |
maxVoices Most simultaneous voices when not interrupting. | number | 4 |
destination null leaves output unconnected. | AudioNode | null | speakers |
Returns
| Prop | Type | Default |
|---|---|---|
play / stop | () => void | — |
isPlaying / isLoaded | boolean | — |
duration Seconds. | number | — |
progress 0..1 while playing. | FrameSource<number> | — |
output The sound's output node. | AudioNode | null | — |
error | Error | null | — |
loadAudioBuffer(context, src) is exported for preloading.