Sound Hook
ncdai-chirags/use-soundFreeHook
Custom React hook to load and play a sound from a given URL using the Web Audio API.
Install it
npx shadcn@latest add https://www.chirags.dev/r/use-sound.jsonSource
1import { useCallback, useEffect, useRef } from "react";23/**4 * Custom React hook to load and play a sound from a given URL using the Web Audio API.5 *6 * This hook fetches the audio file at the specified URL, decodes it, and prepares it for playback.7 * It returns a `play` function that can be called to play the loaded sound.8 *9 * @param url - The URL of the audio file to load and play.10 * @returns A function that, when called, plays the loaded sound.11 *12 * @remarks13 * - If the Web Audio API is not supported in the browser, a warning is logged and playback is disabled.14 * - The audio context and buffer are managed internally using React refs.15 * - Errors during fetching or decoding the audio are logged to the console.16 *17 * @example18 * ```tsx19 * const playClick = useSound('/sounds/click.mp3');20 * // Later in an event handler:21 * playClick();22 * ```23 */24export function useSound(url: string) {25 const audioCtxRef = useRef<AudioContext | null>(null);26 const bufferRef = useRef<AudioBuffer | null>(null);2728 useEffect(() => {29 const AudioContextClass =30 window.AudioContext ||31 (window as unknown as { webkitAudioContext: typeof AudioContext })32 .webkitAudioContext;3334 if (!AudioContextClass) {35 console.warn("Web Audio API is not supported in this browser.");36 return;37 }3839 const audioCtx = new AudioContextClass();40 audioCtxRef.current = audioCtx;4142 fetch(url)43 .then((res) => res.arrayBuffer())44 .then((data) => audioCtx.decodeAudioData(data))45 .then((decoded) => {46 bufferRef.current = decoded;47 })48 .catch((err) => {49 console.log(`Failed to load click sound from ${url}:`, err);50 });51 }, [url]);5253 const play = useCallback((volume: number = 1) => {54 if (audioCtxRef.current && bufferRef.current) {55 const source = audioCtxRef.current.createBufferSource();56 const gainNode = audioCtxRef.current.createGain();5758 source.buffer = bufferRef.current;59 gainNode.gain.value = volume;6061 source.connect(gainNode);62 gainNode.connect(audioCtxRef.current.destination);63 source.start(0);64 }65 }, []);6667 return play;68}
Files it writes
More from ncdai
All 28 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Controllable State Hookuse-controllable-state | ncdai | Hooks | Free | no deps · 2 files |
