Audio Waveform

A live visualiser for an HTML audio source, driven by WebAudio's AnalyserNode.

ByMihirJaiswalUpdated

Loading...

Audio Waveform is a React visualiser that reacts in real time to an HTML <audio> element, driven by WebAudio's AnalyserNode. It supports a mirrored-bars mode and a continuous waveform line, and it exposes a ref handle with play, pause, toggle, and seek so the surrounding UI can drive playback.

A shared AudioContext is constructed lazily on first play — browsers block it until a user gesture, so playback must come from a click or similar event. Useful for music and podcast UIs, voice-note previews, and any interface where sound needs a visible analogue.

Installation

Usage

import { useRef } from "react";
import {
  AudioWaveform,
  type AudioWaveformHandle,
} from "@/components/ui/audio-waveform";
 
export function Example() {
  const ref = useRef<AudioWaveformHandle>(null);
  return (
    <div className="flex items-center gap-3">
      <button onClick={() => ref.current?.toggle()}>Play / Pause</button>
      <AudioWaveform
        ref={ref}
        src="/track.mp3"
        className="h-10 w-64 text-brand"
      />
    </div>
  );
}

Continuous waveform line

<AudioWaveform src="/track.mp3" mode="wave" className="h-16" />

Props

PropTypeDefaultDescription
srcstring—URL of the audio source.
barCountnumber48Number of frequency bars to draw.
gapnumber3Gap between bars in pixels.
minHeightnumber2Minimum bar height in pixels (idle baseline).
sensitivitynumber1Multiplier on the normalised amplitude.
colorstringcurrentColorFill colour for bars or stroke colour for the wave.
mode"bars" | "wave""bars"Render as mirrored bars or a continuous waveform line.
onPlay() => void—Fires when playback starts.
onPause() => void—Fires when playback pauses or ends.
onFrame(amp: number) => void—Fires every animation frame with the current RMS amplitude.
onProgress(current: number, duration: number) => void—Fires as playback advances, with times in seconds.
showProgressbooleantruePlayed bars solid, the rest dimmed, like a scrubber. Bars mode only.
seekablebooleantrueClick or drag across the waveform to seek.
classNamestring—Extra classes on the wrapper.

Ref handle

MethodSignatureDescription
play() => Promise<void>Resume playback.
pause() => voidPause playback.
toggle() => Promise<void>Toggle play/pause.
seek(seconds: number) => voidSeek the audio element.