Command Palette

Search for a command to run...

SFX/useSound Hook

useSound Hook

React hook for playing sound assets via Web Audio API

Overview

A React hook that wraps the sound engine with state management for play/stop/pause and isPlaying tracking. Installed automatically when you add any sound.

Installation

npx shadcn@latest add @elements/use-sound

Typically you don't need to install this directly - it's pulled in automatically by any sfx-* component.

Usage

import { useSound } from "@/hooks/use-sound";
import { popSound } from "@/sfx/pop";

export function SoundButton() {
  const [play, { stop, isPlaying }] = useSound(popSound, {
    volume: 0.5,
  });

  return (
    <button onClick={isPlaying ? stop : play}>
      {isPlaying ? "Stop" : "Play"}
    </button>
  );
}

API

Parameters

ParameterTypeDescription
soundSoundAssetThe sound asset to play
optionsUseSoundOptionsOptional playback configuration

Options

OptionTypeDefaultDescription
volumenumber1Volume level (0-1)
playbackRatenumber1Playback speed
interruptbooleantrueStop previous playback on new play
onEnd() => void-Callback when playback finishes

Return Value

Returns a tuple [play, controls]:

PropertyTypeDescription
play() => voidStart playback
stop() => voidStop playback
pause() => voidPause playback
isPlayingbooleanWhether sound is currently playing
durationnumberSound duration in seconds
soundSoundAssetThe sound asset reference

License

CC0 (public domain). No attribution required.