Overview
TheuseAudio hook provides a simple interface for controlling audio playback in React components. It manages audio state, playback controls, and includes a smooth fade-out effect for better user experience.
For global audio management across the application, consider using the
AudioProvider context instead. See the Background Audio feature documentation for more details.Import
Usage
Parameters
The URL or path to the audio file to be played
Return Value
The hook returns an object with the following properties:Function to start or resume audio playback. Sets volume to 1 and begins playing.
Function to pause audio playback immediately.
Function to gradually fade out the audio over a specified duration before pausing.Parameters:
duration(optional): Fade duration in milliseconds. Default is1000ms (1 second).
Function to toggle between play and pause states. Calls
pause() if playing, otherwise calls play().Boolean indicating whether the audio is currently playing.
Boolean indicating whether the audio has loaded and is ready to play. Becomes
true when the canplaythrough event fires.React ref containing the underlying HTML audio element. Useful for advanced audio manipulation or accessing native audio properties.
Implementation Details
Audio Loading
The hook creates a newAudio element when the component mounts or when the src changes:
Fade Out Algorithm
ThefadeOut function uses a stepped interval approach:
- Divides the fade duration into 50 steps
- Calculates volume decrement per step
- Uses
setIntervalto gradually reduce volume - Automatically pauses and cleans up when volume reaches 0
Cleanup
The hook automatically cleans up resources when the component unmounts:- Clears any active fade intervals
- Pauses audio playback
- Removes event listeners
Use Cases
- Sound effects: Play button clicks, notifications, or UI feedback sounds
- Background music: Add ambient audio to specific pages or sections
- Audio previews: Preview audio files before full playback
- Voiceovers: Control narration or guided tour audio
Related
- Background Audio - Global audio management with user consent
- State Management - AudioProvider context for app-wide audio control
