LabDAW

Waveform

Draws audio: a seekable waveform with regions and markers, a live waveform that scrolls with the signal, and a bar visualizer.

Components for drawing audio. Waveform shows a whole file and lets you scrub through it. LiveWaveform follows a signal as it plays. BarVisualizer turns that signal into a few bars you style in CSS. All three are written on the waveform primitive, which installs with them and works with any audio: decoded PCM samples, a microphone or a stream from your server.

Overview

  • Two kinds of data: a file's shape is known in advance, so Waveform takes values (amplitudes from 0 to 1, at any resolution). A live signal is not, so LiveWaveform and BarVisualizer take a source and follow it outside React.
  • Value: value is the playback position, from 0 to duration (default 1, a fraction; pass the track length in seconds to work in seconds). The primitive owns the seek position, not the audio: connect onValueChange to your own <audio> element.
  • Asymmetric shape: give values the lowest and highest sample of each slice ({ min, max }) and the waveform is drawn asymmetric, as in a DAW. Plain amplitudes draw the same shape above and below the middle.
  • Part of the audio: range shows only a stretch of the audio, such as a clip's window onto its source or a zoomed view. The playhead, seeking, hover, regions and markers follow that stretch. See Showing part of the audio.
  • Resolution: the canvas draws as many bars as fit its width and keeps the loudest sample of each bar's slice, so detail holds at any size. Bars align to physical pixels, so their edges stay sharp at any pixel density or zoom. See Feeding real audio.
  • Shapes: shape="mirror" (the default) centers the bars, "bars" stands them on the baseline, and "line" joins the levels into one shape. A live waveform can also be a "scope": raw samples traced as one line, like an oscilloscope.
  • On the timeline: WaveformRegion is a stretch you can move and resize, such as a loop. WaveformMarker is a labelled point. WaveformHover follows the pointer and shows the time under it.
  • Performance: moving parts are painted outside React, and only when something changes. A waveform that is off screen or at rest uses no frames. When reduced motion is requested, live waveforms repaint a few times per second, without smoothing or idle animation.
  • Accessibility: the seekable waveform holds a native <input type="range">: it takes focus, carries aria-label, announces the played share (or the text from getAriaValueText, such as a time), and supports the arrow keys, Home, End, Page Up and Page Down. Each region handle holds one too. Live waveforms are images: give them an aria-label.

Installation

The primitives are built on the UI SDK kernel, in beta. Nothing of ours comes from npm: the primitive and its adapter are files you copy into your project and own, and the only packages are the kernel's. The commands name its version, @ui-sdk/*@0.1.0-beta.14.

The styled component, with the seekable waveform, the live waveform and the bar visualizer, is one command:

The styled component, with size variants and theme styles:

pnpm dlx shadcn@latest add @audio-ui/waveform

Or the primitive alone, to style yourself:

pnpm dlx shadcn@latest add @audio-ui/waveform-react

It writes the primitive, its adapter and primitive.ts into components/audio-ui/ and installs the kernel's packages and what each file imports. The optional styles are one more command:

pnpm dlx shadcn@latest add @audio-ui/primitives-css

Usage

import {
  BarVisualizer,
  LiveWaveform,
  Waveform,
  WaveformHover,
  WaveformMarker,
  WaveformRegion,
  WaveformRegionHandle,
} from "@/components/audio-ui/waveform";

A file, in seconds, with a playhead line and handle:

<Waveform
  aria-label="Track progress"
  duration={audio.duration}
  onValueChange={(seconds) => {
    audio.currentTime = seconds;
  }}
  value={currentTime}
  values={values}
  variant="playhead"
/>

A live waveform, scrolling with a made-up voice:

A microphone, scrolling as it comes in:

const { level } = useAudioSignal(analyser);

<LiveWaveform aria-label="Microphone input" mode="scrolling" source={level} />;

A voice, as bars:

const { bands } = useAudioSignal(analyser);

<BarVisualizer aria-label="Agent speaking" mirrored source={bands} />;

The primitive alone, part by part:

A Root owns the position and what is shown. Everything else is a part you place in it:

  • Canvas: draws the shape on the device pixel grid, sharp at any density, and only when something changed.
  • Bars and Bar: the shape as a fixed number of elements, styled in plain CSS from --waveform-level.
  • Control: the seekable surface. A press jumps to the pointer and a drag scrubs. It holds the native <input type="range"> that takes focus and the keys, and carries the accessible name.
  • Playhead and Thumb: follow the position through the --waveform-position CSS variable.
  • Hover: shown at the hovered point, with the text format returns.
  • Marker: a point of interest at a value.
  • Region and RegionHandle: a named stretch laid over the waveform, moved by its body and resized by its edges.
import { Waveform } from "@/components/audio-ui/waveform/react";

export function Player({ peaks, time, onSeek }: { peaks: number[]; time: number; onSeek: (time: number) => void }) {
  return (
    <Waveform.Root duration={120} onValueChange={onSeek} peaks={peaks} value={time}>
      <Waveform.Control aria-label="Position" className="relative h-16">
        <Waveform.Canvas className="absolute inset-0 size-full text-muted-foreground" />
        <Waveform.Playhead className="absolute inset-y-0 w-px bg-primary" />
      </Waveform.Control>
    </Waveform.Root>
  );
}

A live position and a live signal

Give the Root a source, a live position in duration units in the shape of an external store: getSnapshot() returns it and subscribe(listener) is called on each tick. The --waveform-position variable, the Canvas and the input follow it straight in the DOM, with no render. levels is the same for a signal, such as a microphone or an analyser: each value is a level from 0 to 1, and while it is audible the Root carries data-active. Any object with those two methods works, with nothing to install.

Feeding real audio

values is a plain prop: the component does not decode audio. @/lib/engine/analysis and the audio-decode lib (npx shadcn@latest add @audio-ui/audio-decode) turn a real audio file into values: decodeAudioChannels (from audio-decode) reads every channel's PCM samples at the context's sample rate, with the browser's own decoder, or for an AIFF, CAF or Apple Lossless file it refuses, as Chrome does, a decoder of its format and a resampler, loaded the first time one is needed; computePeaks reduces them to each slice's lowest and highest sample across all channels (so a take panned hard to one side still draws), and normalizePeaks scales them so the loudest sample reaches full height.

import { computePeaks, normalizePeaks } from "@/lib/engine/analysis";
import { decodeAudioChannels } from "@/lib/engine/files";

const context = new AudioContext();
const channels = await decodeAudioChannels(context, await file.arrayBuffer());

const values = normalizePeaks(computePeaks(channels, 4096));

The second argument to computePeaks is a resolution, not a bar count: the canvas fits whatever you pass to its own width and to any range. Compute it once per file, with more slices than the widest view you expect will show (a few thousand covers a zoomed-in clip editor). For a simpler shape, downsampleWaveform and normalizeWaveform give one amplitude per slice instead.

Showing part of the audio

range is the stretch of the audio to show, [start, end] in duration units. Everything follows it: the bars are drawn from that stretch of values alone, a press seeks inside it, the input's keys stay inside it, and regions and markers are placed across it.

<Waveform
  aria-label="Clip"
  duration={source.duration}
  range={[clip.offset, clip.offset + clip.length]}
  values={source.peaks}
/>

When the position is outside the stretch, the root carries data-outside and the playhead is hidden, rather than pinned to an edge it hasn't reached. Past the largest canvas a browser will draw (16,384 pixels a side), the bitmap is drawn coarser rather than going blank.

Following playback

value re-renders React each time it changes, which is fine for a timeupdate event a few times a second. For a playhead that glides every animation frame, pass a source, an object in the shape of an external store:

interface WaveformSource {
  getSnapshot: () => number; // the position, in `duration` units
  subscribe: (listener: () => void) => () => void;
}

The waveform subscribes to it and moves the playhead, repaints the canvas and updates the input itself. While the pointer scrubs, the waveform follows the pointer and ignores the source until release; the same holds for a controlled value that updates late.

Regions and markers

Anything inside Waveform is laid over the canvas, on the same timeline. A region is [start, end] in duration units; drag its body to move it, and give it a handle per edge to resize it:

const [loop, setLoop] = useState<readonly [number, number]>([48, 96]);

<Waveform aria-label="Track progress" duration={180} values={values}>
  <WaveformRegion onValueChange={setLoop} value={loop}>
    <WaveformRegionHandle aria-label="Loop start" edge="start" />
    <WaveformRegionHandle aria-label="Loop end" edge="end" />
  </WaveformRegion>
  <WaveformMarker value={124}>Chorus</WaveformMarker>
  <WaveformHover format={formatTime} />
</Waveform>

A press on a region never seeks the waveform underneath. Each handle is a slider of its own: it takes focus, and the arrow keys, Page Up / Page Down, Home and End move its edge, which stops minLength short of the other one. Leave the handles out for a region that only moves, or pass movable={false} for one that only resizes.

Live signals

A live waveform reads from a source, an object in the shape of an external store whose snapshot is the current levels, 0–1 each:

interface LevelsSource {
  getSnapshot: () => ArrayLike<number>;
  subscribe: (listener: () => void) => () => void;
}

The use-audio-signal hook (npx shadcn@latest add @audio-ui/use-audio-signal) reads two of them from an AnalyserNode, every animation frame and only while something is drawing them:

const { level, bands, samples } = useAudioSignal(analyser, { bandCount: 32 });
  • level is the loudest sample of the moment, as a single level. Draw it with mode="scrolling": the waveform records it over time, the newest entering from the right, or from the middle outwards with mirrored. When the signal stops (pass null as the analyser to pause), the trace holds still.
  • bands is the spectrum as log-spaced frequency bands, low to high. Draw it with a BarVisualizer, or a LiveWaveform in its default mode="static": the bars stay in place and follow the bands, rising at once and falling smoothly.
  • samples is the raw waveform of the moment, -1 to 1. Draw it with shape="scope".

Any signal works. A source is an object with getSnapshot() and subscribe(listener), which you push to yourself, from a WebSocket, a worklet or a test:

let frame = new Float32Array(16);
const listeners = new Set<() => void>();

const levels = {
  getSnapshot: () => frame,
  subscribe(listener: () => void) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  },
};

socket.onmessage = (event) => {
  frame = event.data;
  for (const listener of listeners) listener();
};

While its signal is audible, a live waveform carries data-active. idle picks what the bars do meanwhile ("pulse" breathes, "wave" ripples), and loading sweeps across them while a connection is on its way.

Theming

Colors come from CSS, and the canvas repaints when the theme changes:

CSS variables · 5

--waveform-position
Set on the root: the playback position, as a percentage.
--waveform-level
Set on each bar of a BarVisualizer: its level, 0–1.

The bars of a BarVisualizer are plain elements: restyle them with .cn-bar-visualizer-bar. Those the playback position has passed carry data-played.

Interaction

Control

  • A press seeks, a drag scrubs, and the end of the gesture commits.
  • Shift with a drag selects a stretch instead, reported to onSelectionChange and onSelectionCommitted. Without them a Shift drag is an ordinary seek.
  • The arrows move by step, Shift with an arrow and Page Up and Page Down by largeStep, Home and End go to the ends.
  • Nothing seeks while disabled or loading.

Regions

  • Dragging a Region's body moves it, unless movable is false. Dragging a RegionHandle resizes that edge.
  • On a handle's input, the arrows and Page keys move the edge and Home and End send it to its limit.
  • A press on a region never reaches the Control underneath.

API reference

Registry component

aria-label, aria-labelledby, and aria-describedby are forwarded to the element that needs them: the waveform's input, a region handle's input, or the live waveform itself.

Waveform

Props · 20

WaveformRegion

Props · 7

WaveformRegionHandle takes edge ("start" or "end") and getAriaValueText. WaveformMarker takes value and shows its children as a label. WaveformHover takes format, which prints the hovered position; without it only the line shows.

LiveWaveform

Props · 8

BarVisualizer

Props · 9

The Waveform primitive that installs with it exposes the parts these components are built from:

Parts · 8

Waveform.Root
Owns the data (peaks, or a live levels source) and the position (value, source, duration). Carries data-active while a live signal is audible.
Waveform.Control
The seekable surface; holds the input. Leave it out for a waveform that is only shown.
Waveform.Canvas
Draws on a canvas: variant, mode, scrollSpeed, barWidth, barGap, barRadius, minBarHeight, lineWidth, gain, mirrored, idle.
Waveform.Bars, Waveform.Bar
Draws as elements: count, minLevel, gain, mirrored, idle. Each bar gets --waveform-level, data-index and data-played.
Waveform.Region, Waveform.RegionHandle
A stretch of the timeline, named by region, and the handle of one of its edges. What they report goes to the Root's onRegionChange and onRegionCommitted, with the region's name in the details.
Waveform.Marker
A point on the timeline.
Waveform.Playhead, Waveform.Thumb
Follow the playback position.
Waveform.Hover
Shown at the hovered position; its format turns that position into the text it writes.

Every part accepts a render prop and className / style as functions of state, and exposes that state as data attributes such as data-disabled, data-dragging and data-loading.

Options

Set on the Root, as props (an attribute in kebab case in the web adapter).

OptionTypeDefault
value, defaultValuenumber0The position, controlled or starting.
source{ getSnapshot, subscribe }A live position, followed with no render. It takes precedence over value.
durationnumber1The length of the audio, in the unit value is in.
peaksnumber[] or { min, max }[]The shape, at any resolution: a level per slice, or the lowest and highest sample of each.
levels{ getSnapshot, subscribe }A live signal drawn instead of peaks.
range[start, end]the whole audioThe stretch shown. The position, seeking, hover, regions and markers follow it.
step, largeStepnumbera hundredth, a tenth of durationThe keys' steps.
loadingbooleanfalseThe audio is still on its way. Seeking waits.
disabledbooleanfalseTakes no gesture.
namestringThe form field's name, carried by the seek input.
onValueChange, onValueCommitted(value, details) => voidA seek, and its end.
onSelectionChange, onSelectionCommitted(range, details) => voidA Shift drag.
onRegionChange, onRegionCommitted(region, details) => voidA region moved or resized, with details.region and details.edge.

A Region takes region (its name), value or defaultValue ([start, end]), minLength, movable and disabled; a RegionHandle takes edge and the same region. The Canvas takes variant, mode, barWidth, barGap, barRadius, gain, idle and the rest of the painter's options, the Bars count, gain, idle, minLevel and mirrored. Colors come from --waveform-color and --waveform-progress-color.

What a change reports

details carries:

  • reason: "press", "drag", "keyboard" or "input-change".
  • source: "mouse", "touch", "pen", "keyboard", "programmatic" or "agent".
  • event and cancel(): the DOM event behind it, and the refusal.
  • For a region, region (its name) and edge ("start", "end" or "both").

In the web adapter, the seek is the input and change events, and the selection and the regions are selectionchange, selectioncommit, regionchange and regioncommit, each with a detail of the value and its reasons. event.preventDefault() refuses a change.

States to style from

  • data-dragging while a pointer scrubs or selects, data-loading, data-disabled on every part.
  • data-active on the Root while a live signal is audible, and data-outside while the position is outside the stretch shown.
  • data-played on the bars the position has passed, data-index on a bar, data-region and data-edge on a region and its handles.

Parts

Parts · 11

Events

Events · 6

Built by Ouest Labs, the source code is available on GitHub.
RSS