Skip to content

useAudio

Hook to use an HTML audio element.

Demo

INFO

The component use useAudio hook to use an audio track.

Loading demo…
Show source code
tsx
import { useAudio } from "../../../..";
import audio from '../../../../assets/bubbles.mp3';

export const UseAudio = () => {
	const {MediaElement, state, controls: {play, pause}} = useAudio({ src: audio, controls: true });

	return <div>
		{MediaElement}
		<p>Status: {state.paused ? "paused" : state.playing ? "playing" : "ready"}</p>
		<button onClick={play} disabled={state.playing}>Play</button>
		<button onClick={pause} disabled={state.paused}>Pause</button>
	</div>
}

Types

UseAudioProps

Props accepted by useAudio.

These are the standard HTMLAudioElement attributes you would normally pass to a <audio> tag (e.g. src, autoPlay, loop, controls, muted, etc.). All attributes are optional.

The hook creates the audio element internally and binds these attributes to it, so you do not need to render an <audio> tag yourself — use the returned MediaElement instead.

ts
export type UseAudioProps = MediaHTMLAttributes<HTMLAudioElement>

UseAudioResult

Result object returned by useAudio.

PropertyTypeRequiredDescription
stateHTMLMediaStateReactive snapshot of the current audio element state. Re-renders the component whenever a media event fires. See {@link HTMLMediaState} for the full list of fields.
controlsHTMLMediaControlsImperative control functions for the audio element (play, pause, mute, seek, volume, etc.). All functions are stable references and safe to call in event handlers. See {@link HTMLMediaControls} for the full API.
MediaElementDetailedReactHTMLElement<HTMLAttributes<HTMLAudioElement>, HTMLAudioElement>The React &lt;audio&gt; element to render in JSX. Rendering this element is required for the hook to function — it binds the internal ref and event listeners to the DOM node.
refMutableRefObject<HTMLAudioElement \| null>Direct ref to the underlying HTMLAudioElement. Useful for advanced imperative access not covered by controls. null before the element mounts.

Released under the MIT License.