useAudio

A React hook providing a declarative and unopinionated interface to manage the HTML5 Audio API lifecycle.

Warning

Browsers often block audio from playing automatically (autoplay) unless the user has interacted with the domain first or the audio is muted.

Caution

When the src changes, the hook creates a new Audio instance. Ensure you handle state cleanup in your UI if you are switching tracks rapidly to avoid overlapping sounds.

Installation

bash

Description

The useAudio abstracts the complexity of the HTMLAudioElement, offering reactive state tracking for audio playback status (playing, paused, loading, etc.) and error handling. It manages the internal audio instance, ensuring that event listeners are correctly cleaned up and audio is paused when the component unmounts to prevent memory leaks or ghost audio.

Parameters

NameTypeDescription
options.srcstringThe URL of the audio file to be loaded.
options.loopbooleanWhether the audio should start over again when it reaches the end. Default: false
options.volumenumberThe volume level, ranging from 0.0 to 1.0. Default: 1.0

Return values

NameTypeDescription
audioHTMLAudioElement | nullThe underlying native audio instance for advanced direct manipulation.
errorError | nullContains an error object if the audio fails to load or play.
pause() => voidFunction to pause the current playback.
play() => Promise<void>Async function to start playback; handles the browser's play promise.
statusAudioStatusReactive string representing the current state: 'idle', 'loading', etc.

Demo

Audio

Status: idleError:

Source code

tsx