WarningBrowsers often block audio from playing automatically (autoplay) unless the user has interacted with the domain first or the audio is muted.
CautionWhen 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.
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.
| 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 |
| 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. |