useSoundEffects
NewuseSoundEffects plays short interface sounds that are synthesized with Web Audio on the fly: nothing to download, nothing to host. It ships click, success, error and complete, takes your own presets and remembers the on/off switch in localStorage.
Preview
Volume
The switch is saved in localStorage and survives a reload.
Installation
Usage
import { Button } from "@/components/ui/button"
import { useSoundEffects } from "@/hooks/use-sound-effects"
export function SubmitButton() {
const { play } = useSoundEffects()
async function submit() {
play("click")
const ok = await save()
play(ok ? "success" : "error")
}
return <Button onClick={submit}>Save</Button>
}Examples
Your own presets
A preset is a list of notes: pitch, length, delay, waveform and an optional glide. Custom names are typed, play() suggests them.
const sounds = {
pop: [{ frequency: 400, slideTo: 1200, duration: 0.08 }],
coin: [
{ frequency: 988, duration: 0.08, type: "square", gain: 0.3 },
{ frequency: 1319, duration: 0.3, delay: 0.07, type: "square", gain: 0.3 },
],
} satisfies Record<string, SoundPreset>
const { play } = useSoundEffects({ sounds })
play("coin")Sound toggle
enabled lives in localStorage and is shared by every component with the same storageKey. Start muted with defaultEnabled.
import { Button } from "@/components/ui/button"
const { enabled, toggle } = useSoundEffects({ defaultEnabled: false })
<Button role="switch" aria-checked={enabled} onClick={toggle}>
{enabled ? <Volume2 /> : <VolumeX />}
</Button>Volume
Volume is a plain option from 0 to 1, so you can drive it from state or settings.
const [volume, setVolume] = useState(0.3)
const { play } = useSoundEffects({ volume })Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| options.sounds | Record<string, SoundPreset> | - | Extra presets, merged over the built-in ones |
| options.volume | number | 0.5 | Master volume from 0 to 1 |
| options.storageKey | string | "gooseui-sounds" | localStorage key for the on/off switch |
| options.defaultEnabled | boolean | true | Used until the user flips the switch |
Returns
| Name | Type | Description |
|---|---|---|
| play | (name) => void | Plays a preset by name. Does nothing while sound is off |
| enabled | boolean | Current switch state |
| setEnabled | (value: boolean) => void | Turn sound on or off and save it |
| toggle | () => void | Flip the switch |
| defaultSounds | Record<string, SoundPreset> | Separate export with the built-in presets |
Features
- Autoplay policy. The AudioContext is created on the first pointer or key press and reused by every call
- No files. Every sound is a few oscillators with a short envelope, so there is no click at the start or end
- Cleans up nodes. Oscillators and gain nodes are disconnected as soon as a note ends
- Survives blocked storage. If localStorage is unavailable, the switch is kept in memory for the page