MediaAdvancedSSR-safehooks/media/useAudio.ts

useAudio

Control an HTMLAudioElement.

Import

TypeScript
import { useAudio } from '@/hooks';

API

Signature

useAudio(options?) → playback controls

When to use

Use useAudio instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-only browser APIs.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useAudio
Editor
function Player() {
  const audio = useAudio({ src: '/demo.mp3' });
  return (
    <div>
      <button onClick={() => void audio.play()}>Play</button>
      <button onClick={audio.pause}>Pause</button>
      <p>{audio.time.toFixed(1)} / {audio.duration.toFixed(1)}</p>
    </div>
  );
}
Preview

Implementation source

Full library source for useAudio — copy into your project when you are not installing a package yet.

hooks/media/useAudio.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';

export interface UseAudioOptions {
  src?: string;
  autoPlay?: boolean;
  loop?: boolean;
  volume?: number;
}

/** Lightweight HTMLAudioElement controller. */
export function useAudio(options: UseAudioOptions = {}) {
  const { src, autoPlay = false, loop = false, volume = 1 } = options;
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [playing, setPlaying] = useState(false);
  const [duration, setDuration] = useState(0);
  const [time, setTime] = useState(0);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    if (!isBrowser()) return;
    const audio = new Audio(src);
    audio.loop = loop;
    audio.volume = volume;
    audioRef.current = audio;

    const onPlay = () => setPlaying(true);
    const onPause = () => setPlaying(false);
    const onTime = () => setTime(audio.currentTime);
    const onMeta = () => setDuration(audio.duration || 0);
    const onError = () => setError(new Error('Audio failed to load'));

    audio.addEventListener('play', onPlay);
    audio.addEventListener('pause', onPause);
    audio.addEventListener('timeupdate', onTime);
    audio.addEventListener('loadedmetadata', onMeta);
    audio.addEventListener('error', onError);

    if (autoPlay) void audio.play().catch(() => undefined);

    return () => {
      audio.pause();
      audio.src = '';
      audio.removeEventListener('play', onPlay);
      audio.removeEventListener('pause', onPause);
      audio.removeEventListener('timeupdate', onTime);
      audio.removeEventListener('loadedmetadata', onMeta);
      audio.removeEventListener('error', onError);
      audioRef.current = null;
    };
  }, [src, autoPlay, loop, volume]);

  const play = useCallback(async () => {
    await audioRef.current?.play();
  }, []);
  const pause = useCallback(() => audioRef.current?.pause(), []);
  const toggle = useCallback(() => {
    if (playing) pause();
    else void play();
  }, [playing, play, pause]);
  const seek = useCallback((t: number) => {
    if (audioRef.current) audioRef.current.currentTime = t;
  }, []);

  return {
    playing,
    duration,
    time,
    error,
    play,
    pause,
    toggle,
    seek,
    audio: audioRef,
  };
}

Copy-paste example

useAudio.example.tsx
'use client';

import { useAudio } from '@/hooks';

export function Player() {
  const audio = useAudio({ src: '/demo.mp3' });
  return (
    <div>
      <button onClick={() => void audio.play()}>Play</button>
      <button onClick={audio.pause}>Pause</button>
      <p>{audio.time.toFixed(1)} / {audio.duration.toFixed(1)}</p>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Always stop tracks on unmount (hooks clean up streams they own).
  • Source of truth: open hooks/media/useAudio.ts for implementation details