frontend.fyi
Overview

useSound() — Add small sounds effects to your page

No sound? Browsers require you to interact with the page first (e.g. click somewhere), before you can play sounds.

import { useEffect, useRef } from "react";
type Settings = {
volume?: number;
playbackRate?: number;
};
export const useSound = (url: string, settings: Settings | undefined = {}) => {
const audioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
// If the url changes, we clear the old instance,
// this way a new Audio instance will be created on the next play
audioRef.current = null;
}, [url]);
useEffect(() => {
if (!audioRef.current) return;
audioRef.current.volume = settings.volume || 1;
audioRef.current.playbackRate = settings.playbackRate || 1;
}, [settings]);
const play = () => {
if (typeof window === "undefined") return;
if (!audioRef.current) {
// We only created the Audio instance when play is fired,
// this way we can avoid loading the sound if it's not used
audioRef.current = new Audio(url);
}
try {
audioRef.current.currentTime = 0;
audioRef.current.play();
} catch {}
};
return [play];
};
import { useEffect, useRef } from "react";
export const useSound = (url, settings = {}) => {
const audioRef = useRef(null);
useEffect(() => {
// If the url changes, we clear the old instance,
// this way a new Audio instance will be created on the next play
audioRef.current = null;
}, [url]);
useEffect(() => {
if (!audioRef.current) return;
audioRef.current.volume = settings.volume || 1;
audioRef.current.playbackRate = settings.playbackRate || 1;
}, [settings]);
const play = () => {
if (typeof window === "undefined") return;
if (!audioRef.current) {
// We only created the Audio instance when play is fired,
// this way we can avoid loading the sound if it's not used
audioRef.current = new Audio(url);
}
try {
audioRef.current.currentTime = 0;
audioRef.current.play();
} catch {}
};
return [play];
};

Subtle sounds can add some life to your page ✨. They make it feel more interactive and engaging.

After using Josh Comeau’s hook useSound for quite a while, I kept stumbling on a few issues with the package that didn’t get fixed. Probably because Josh also moved on from this library.

That is why I decided to write my own basic implementation of the useSound hook. The implementation is based around the standardized Web Audio API. That means we need pretty little code to make a small hook that plays a sound.

Using the hook

To use the hook, you need to pass the URL of the sound you want to play. Optionally you can pass an object with the volume and playback rate settings.

The hook then returns an array with a single function (for now 😉), which you can call to play the sound.

import { useSound } from "./useSound";
const MyComponent = () => {
const [play] = useSound("/path/to/sound.mp3", {
volume: 0.5,
playbackRate: 1.5,
});
return <button onClick={play}>Play sound</button>;
};