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
Waveformtakesvalues(amplitudes from0to1, at any resolution). A live signal is not, soLiveWaveformandBarVisualizertake asourceand follow it outside React. - Value:
valueis the playback position, from0toduration(default1, a fraction; pass the track length in seconds to work in seconds). The primitive owns the seek position, not the audio: connectonValueChangeto your own<audio>element. - Asymmetric shape: give
valuesthe 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:
rangeshows 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:
WaveformRegionis a stretch you can move and resize, such as a loop.WaveformMarkeris a labelled point.WaveformHoverfollows 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, carriesaria-label, announces the played share (or the text fromgetAriaValueText, 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 anaria-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:
Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/waveform
Or the primitive alone, to style yourself:
Copy to Clipboardpnpm 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:
Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/primitives-css
Usage
Copy to Clipboardimport { BarVisualizer, LiveWaveform, Waveform, WaveformHover, WaveformMarker, WaveformRegion, WaveformRegionHandle, } from "@/components/audio-ui/waveform";
A file, in seconds, with a playhead line and handle:
Copy to Clipboard<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:
Copy to Clipboardconst { level } = useAudioSignal(analyser); <LiveWaveform aria-label="Microphone input" mode="scrolling" source={level} />;
A voice, as bars:
Copy to Clipboardconst { 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-positionCSS variable. - Hover: shown at the hovered point, with the text
formatreturns. - 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.
Copy to Clipboardimport { 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.
Copy to Clipboardimport { 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.
Copy to Clipboard<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:
Copy to Clipboardinterface 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:
Copy to Clipboardconst [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:
Copy to Clipboardinterface 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:
Copy to Clipboardconst { level, bands, samples } = useAudioSignal(analyser, { bandCount: 32 });
levelis the loudest sample of the moment, as a single level. Draw it withmode="scrolling": the waveform records it over time, the newest entering from the right, or from the middle outwards withmirrored. When the signal stops (passnullas the analyser to pause), the trace holds still.bandsis the spectrum as log-spaced frequency bands, low to high. Draw it with aBarVisualizer, or aLiveWaveformin its defaultmode="static": the bars stay in place and follow the bands, rising at once and falling smoothly.samplesis the raw waveform of the moment,-1to1. Draw it withshape="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:
Copy to Clipboardlet 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--waveform-levelBarVisualizer: 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
onSelectionChangeandonSelectionCommitted. Without them a Shift drag is an ordinary seek. - The arrows move by
step, Shift with an arrow and Page Up and Page Down bylargeStep, Home and End go to the ends. - Nothing seeks while
disabledorloading.
Regions
- Dragging a Region's body moves it, unless
movableis 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
0–1 amplitudes, or each slice's lowest and highest sample, -1–1.[start, end] in duration units: a clip's window onto its source, a zoomed view. The playhead, seeking, hover, regions and markers all follow it. Defaults to the whole audio. While the position is outside it, the root carries data-outside.0 to duration.value.value is in (typically seconds).duration.duration.eventDetails.reason is "press", "drag", "keyboard", or "input-change"; call eventDetails.cancel() to reject it."0:12 of 1:42". Defaults to the played share, e.g. "30%".[start, end] in duration units; feed it to a Waveform.Region. A plain press and drag still seek. eventDetails.cancel() keeps the selection as it was.playhead adds a playhead line and a handle.WaveformRegion
Props · 7
[start, end] in duration units.duration units. Defaults to the root's step.eventDetails.edge is "start", "end" or "both"; eventDetails.reason is "drag", "keyboard" or "input-change".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
value.static spreads the current levels across the width; scrolling records the loudest one over time.scope traces raw samples instead of levels.static mode, what the bars do while there is no signal.BarVisualizer
Props · 9
value.vertical stacks the bars and grows them sideways.The Waveform primitive that installs with it exposes the parts these components are built from:
Parts · 8
Waveform.Rootpeaks, or a live levels source) and the position (value, source, duration). Carries data-active while a live signal is audible.Waveform.ControlWaveform.Canvasvariant, mode, scrollSpeed, barWidth, barGap, barRadius, minBarHeight, lineWidth, gain, mirrored, idle.Waveform.Bars, Waveform.Barcount, minLevel, gain, mirrored, idle. Each bar gets --waveform-level, data-index and data-played.Waveform.Region, Waveform.RegionHandleregion, 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.MarkerWaveform.Playhead, Waveform.ThumbWaveform.Hoverformat 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).
| Option | Type | Default | |
|---|---|---|---|
value, defaultValue | number | 0 | The position, controlled or starting. |
source | { getSnapshot, subscribe } | A live position, followed with no render. It takes precedence over value. | |
duration | number | 1 | The length of the audio, in the unit value is in. |
peaks | number[] 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 audio | The stretch shown. The position, seeking, hover, regions and markers follow it. |
step, largeStep | number | a hundredth, a tenth of duration | The keys' steps. |
loading | boolean | false | The audio is still on its way. Seeking waits. |
disabled | boolean | false | Takes no gesture. |
name | string | The form field's name, carried by the seek input. | |
onValueChange, onValueCommitted | (value, details) => void | A seek, and its end. | |
onSelectionChange, onSelectionCommitted | (range, details) => void | A Shift drag. | |
onRegionChange, onRegionCommitted | (region, details) => void | A 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".eventandcancel(): the DOM event behind it, and the refusal.- For a region,
region(its name) andedge("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-draggingwhile a pointer scrubs or selects,data-loading,data-disabledon every part.data-activeon the Root while a live signal is audible, anddata-outsidewhile the position is outside the stretch shown.data-playedon the bars the position has passed,data-indexon a bar,data-regionanddata-edgeon a region and its handles.
Parts
Parts · 11
index: key.count: number, gain: number, idle: string, minLevel: number, mirrored: boolean.barGap: number, barRadius: number, barWidth: number, gain: number, idle: string, lineWidth: number, minBarHeight: number, mirrored: boolean, mode: string, scrollSpeed: number, variant: string.format: value.value: number.defaultValue: value, disabled: boolean, minLength: number, movable: boolean, region: key, value: value.Events
Events · 6
@region-change. Web: the regionchange event.@region-committed. Web: the regioncommit event.@selection-change. Web: the selectionchange event.@selection-committed. Web: the selectioncommit event.@value-change. Web: the input event.@value-committed. Web: the change event.