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
Name
Type
Description
options.src
string
The URL of the audio file to be loaded.
options.loop
boolean
Whether the audio should start over again when it reaches the end. Default: false
options.volume
number
The volume level, ranging from 0.0 to 1.0. Default: 1.0
Return values
Name
Type
Description
audio
HTMLAudioElement | null
The underlying native audio instance for advanced direct manipulation.
error
Error | null
Contains an error object if the audio fails to load or play.
pause
() => void
Function to pause the current playback.
play
() => Promise<void>
Async function to start playback; handles the browser's play promise.
status
AudioStatus
Reactive string representing the current state: 'idle', 'loading', etc.