frontend.fyi

useSound()

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.

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

1
type Settings = {
2
volume?: number;
3
playbackRate?: number;
4
};
5
6
export const useSound = (
7
url: string,
8
{ volume, playbackRate }: Settings | undefined = {},
9
) => {
10
// Prevents the hook from crashing in a non-browser environment
11
const audio = typeof window !== "undefined" ? new window.Audio(url) : null;
12
13
if (audio) {
14
audio.volume = volume || 1;
15
audio.playbackRate = playbackRate || 1;
16
}
17
18
const play = () => {
19
if (!audio) return;
20
try {
21
audio.currentTime = 0;
22
audio.play();
23
} catch {}
24
};
25
26
return [play];
27
};
1
export const useSound = (
2
url,
3
{ volume, playbackRate } = {},
4
) => {
5
// Prevents the hook from crashing in a non-browser environment
6
const audio = typeof window !== "undefined" ? new window.Audio(url) : null;
7
8
if (audio) {
9
audio.volume = volume || 1;
10
audio.playbackRate = playbackRate || 1;
11
}
12
13
const play = () => {
14
if (!audio) return;
15
try {
16
audio.currentTime = 0;
17
audio.play();
18
} catch {}
19
};
20
21
return [play];
22
};

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.

1
import { useSound } from "./useSound";
2
3
const MyComponent = () => {
4
const [play] = useSound("/path/to/sound.mp3", {
5
volume: 0.5,
6
playbackRate: 1.5,
7
});
8
9
return (
10
<button onClick={play}>
11
Play sound
12
</button>
13
);
14
};

Changelog

  • 2024-05-28: Added the initial version of the hook.