Loading Audio
The tracks of a multitrack playlist belong to an arrangement: the object that owns the tracks and their clips, the mix, the undo history, and the loading of the audio the clips name. You make it with useCreateArrangement, give it to WebAudioProvider, and change it through its methods. A clip can name its audio (a URL or a file) instead of carrying it; the arrangement fetches and decodes it, and the clip becomes playable when its audio has arrived.
Basic Loading
Declare the tracks in the initializer of useCreateArrangement. audioTrack() from @waveform-playlist/core builds a track with one clip that names its audio:
import { WebAudioProvider, Waveform, useCreateArrangement } from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
function MyEditor() {
// One arrangement per component instance; the initializer runs on the first render only
const arrangement = useCreateArrangement(() => [
audioTrack({ src: '/audio/track1.mp3', name: 'Track 1' }),
audioTrack({ src: '/audio/track2.wav', name: 'Track 2', start: 4 }),
]);
return (
<WebAudioProvider arrangement={arrangement}>
<Waveform />
</WebAudioProvider>
);
}
The playlist is drawn at once, with a row and controls for every track. Nothing is fetched until the provider has its first adapter (the default Tone.js adapter, or the one createAdapter returns): the provider then gives the arrangement its AudioContext to decode with, and each file is fetched and decoded once. A clip is drawn when its audio has decoded, or before that as a placeholder when its length is known.
The initializer and the options of useCreateArrangement are read once. A later render with other values changes nothing: change the arrangement through its methods (below). Keep the same arrangement for the life of the playlist: a new arrangement object passed to the provider mounts everything below it again.
audioTrack() Options
interface AudioTrackOptions {
id?: string; // Track id (default: generated). Must be unique in the arrangement
clipId?: string; // Id of the clip (default: generated)
name?: string; // Track name (default: the file name of src without its extension, else 'Untitled')
src?: ClipSource; // The audio to load: a URL string, a Blob or a File
audioBuffer?: AudioBuffer; // Audio already in memory: nothing is fetched
waveformData?: WaveformDataObject; // Pre-computed peaks (BBC audiowaveform)
start?: number; // Position on the timeline, in seconds (default 0)
duration?: number; // Clip duration in seconds (default: the rest of the source after offset)
offset?: number; // Start within the source, in seconds (default 0)
fadeIn?: Fade;
fadeOut?: Fade;
gain?: number; // Clip gain (default 1)
color?: string; // Waveform color (track and clip)
volume?: number; // Initial volume 0-1 (default 1)
muted?: boolean; // Start muted (default false)
soloed?: boolean; // Start soloed (default false)
pan?: number; // Pan -1 to 1 (default 0)
panLaw?: PanLaw; // 'mono' | 'stereo' (default 'auto': the track's first audio decides)
renderMode?: RenderMode; // 'waveform' | 'spectrogram' | 'both'
spectrogramConfig?: SpectrogramConfig;
spectrogramColorMap?: ColorMapValue;
}
- With
srcand noaudioBuffer, the clip is aLoadingClip: it names its audio, and the arrangement loads it. - With
audioBuffer(with or withoutsrc), or withwaveformDataand nosrc, the clip is anAudioClipbuilt at once. - With none of the three,
audioTrack()throwsaudioTrack: give src, audioBuffer or waveformData. A negative or non-finitestartoroffset, or adurationthat is not a positive number, throws too. - A
durationthat runs past the end of the audio is cut to it, with a console warning.
The mixer fields (volume, muted, soloed, pan) are the values a track enters with. After that the arrangement keeps the mix by track id, and you change it with the mixer setters (useEditorControls().setTrackVolume(trackId, 0.5), arrangement.setTrackVolume(trackId, 0.5)).
Several Clips per Track
A track can hold several clips, each naming a part of a file in seconds. Write the clips as LoadingClip objects on an ArrangementTrack:
import { useCreateArrangement } from '@waveform-playlist/browser';
import { createTrack, type ArrangementTrack, type LoadingClip } from '@waveform-playlist/core';
const buildTracks = (): ArrangementTrack[] => {
const clips: LoadingClip[] = [
{ id: 'synth-a', src: '/audio/synth.mp3', start: 0, duration: 4, offset: 0 },
{ id: 'synth-b', src: '/audio/synth.mp3', start: 8, duration: 4, offset: 4 },
];
return [{ ...createTrack({ name: 'Synth' }), clips }];
};
function MultiClipPlaylist() {
const arrangement = useCreateArrangement(buildTracks);
// ...
}
One URL is one source however many clips name it: it is fetched once, and every clip that names it becomes playable when it has decoded. Give each clip of a track its own id. While its audio loads, a clip cannot be moved, trimmed or split; the clips that have loaded can, and a move or a trim of one stops at the loading clip's span: at its start or its end when its length is known (a duration, or waveformData); when it is not, the loading clip holds its start (one unit of the clip-time grid, a few nanoseconds), which nothing may cover. Clips on a track cannot overlap: when the audio of a clip of unknown length runs into the next clip, the clip ends where the next one starts, with a console warning.
Adding Tracks at Runtime
Change the arrangement through its methods, from an event handler or an effect. The provider and the engine follow; no engine is rebuilt for a track change:
import { useArrangement } from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
// Inside the provider (or call the arrangement you made directly)
function AddFiles() {
const arrangement = useArrangement();
const handleFiles = (files: File[]) => {
const audioFiles = files.filter((file) => file.type.startsWith('audio/'));
if (audioFiles.length === 0) return;
// The user's pick is one undo step, however many files it holds
arrangement.beginTransaction();
try {
// A File is a source by identity; the track is named after the file
for (const file of audioFiles) {
arrangement.addTrack(audioTrack({ src: file }), { undoable: true });
}
} finally {
arrangement.commitTransaction();
}
};
return (
<input
type="file"
accept="audio/*"
multiple
onChange={(e) => handleFiles(Array.from(e.target.files ?? []))}
/>
);
}
What your app adds with arrangement.addTrack(track) is not an undo step: it is the page's content, like a project a DAW opens, and no Undo takes it out (it is written into every undo and redo state as well). Pass { undoable: true } when the add is the user's own edit, such as a dropped or picked file or a "new track" button, and add the tracks of one drop inside beginTransaction() / commitTransaction() so that one Undo takes the whole drop out.
arrangement.removeTrack(id) removes a track as an undo step; arrangement.removeTrack(id, { undoable: false }) removes it for good (no undo brings it back), which suits a dropped file that could not be decoded. arrangement.setTracks([]) removes every track and clears the undo history.
Make these changes from a handler, an effect or a listener of arrangement.sources, not from inside an arrangement.subscribe() listener or an engine statechange listener. Two or more track edits made inside one listener run make the engine send its adapter every track at once (a full setTracks), which can interrupt playback. See Using the Engine Directly.
Loading State and Retry
useArrangementSources(arrangement) returns where each source is:
interface ArrangementSourcesValue {
sources: ReadonlyMap<ClipSource, { status: 'pending' | 'loaded' | 'failed'; error?: Error }>;
pendingCount: number;
failedCount: number;
isLoading: boolean; // true while a source is pending
}
import { useArrangement, useArrangementSources } from '@waveform-playlist/browser';
function LoadingStatus() {
const arrangement = useArrangement();
const { sources, pendingCount, isLoading } = useArrangementSources(arrangement);
const failed = Array.from(sources).filter(([, state]) => state.status === 'failed');
return (
<div>
{isLoading && <span>Loading {pendingCount} file(s)…</span>}
{failed.map(([src, state], i) => (
<span key={i}>
Error loading audio: {state.error?.message}{' '}
<button type="button" onClick={() => arrangement.retry(src)}>
Retry
</button>
</span>
))}
</div>
);
}
The hook takes the arrangement as its argument, so it also works above the provider, with the arrangement you made. arrangement.retry(src) starts a source whose load failed again, and does nothing for any other source. A failed source also shows as failed when its audio loaded but a clip could not be made from it (for example a gain of -1); its error says which clip, and retry changes nothing for it.
Keep the layout above the editor stable while audio loads, for example by drawing a loading indicator as an overlay that takes no space in the layout: a layout change that moves the editor while a clip is being moved leaves the dragged clip at the vertical position it had when the drag started, until the release (the move itself is committed correctly; issue #858).
Common errors are Failed to fetch <url> (a network error or a refused cross-origin request), Failed to fetch <url>: 404 Not Found and the browser's own decode error for a format it cannot decode (that one does not name the file). The URL in a message is cut before its query string, and a user name or password in it is left out.
Placeholders While Audio Loads
A clip whose audio is still loading is not in useTimeline().tracks and is not played. What the view draws for it depends on what the clip says about itself:
| The loading clip has | What is drawn |
|---|---|
waveformData | A placeholder drawn from those peaks, at its place and length |
a duration (no waveformData) | A placeholder box with no waveform in it, at its place and length, filled with the colour the waveform's bars are drawn in (waveFillColor, or selectedWaveFillColor on the selected track; grey when the theme gives no usable colour); it carries data-clip-placeholder-body="true" and is drawn with or without clip headers, on a spectrogram track too |
only a src | Nothing, until its audio has loaded (the track's row and controls are there) |
A placeholder is dimmed (theme key placeholderClipOpacity, 0.5 by default), has no drag handle and no trim handles, and its container carries data-clip-placeholder="true". The box of a placeholder without peaks is <ClipPlaceholderBody /> from @waveform-playlist/ui-components, the clip's first child: the played-portion tint (waveProgressColor) and the fade curves of <WaveformFades /> are drawn over it. Its record is in useTimeline().peaksDataArray with isPlaceholder: true; there is no clip for it in tracks, so look a record up by clipId, not by its position in the row.
No placeholder is drawn until the provider has a sample rate: from mount at the provider's sampleRate prop when you pass it (a request: when the first adapter's context runs at another rate, placeholders are drawn again at that rate), otherwise once its first adapter exists. If the adapter can never be built (a missing optional peer, a createAdapter that throws) and no sampleRate prop is given, no placeholder is ever drawn. Pass sampleRate if placeholders must appear whatever happens to the engine. A placeholder's position and length are at the provider's sample rate, also when its peaks file was made at another rate.
duration in useTimeline() counts loaded audio only. The view is drawn wide enough for a placeholder that ends later. A click on such a placeholder past the end of the loaded audio puts the cursor there; Play from there starts and stops at once, because the position is past the end of the loaded audio, and the cursor stays where it was. seekTo clamps to the loaded audio (a finite time past its end is kept with indefinitePlayback or during a recording session).
Immediate Mode (Progressive Loading)
There is no mode to turn on: every playlist loads progressively. The provider draws at once, a clip with a duration or waveformData shows as a placeholder while its file decodes, and each clip is added to useTimeline().tracks as its file arrives. Play starts working at the first ready, when no file is still loading. (The removed useAudioTracks hook needed { immediate: true } and the provider's deferEngineRebuild for this.)
For instant waveforms of large files, give each clip its pre-computed peaks: see Using Pre-computed Waveforms.
Pre-computed Waveform Data (BBC Peaks)
For large audio files, computing waveforms in the browser can be slow. BBC audiowaveform is a C++ tool that generates waveform data files that can be loaded instantly.
Why Use Pre-computed Waveforms?
| Approach | 10 min file | 1 hour file | 8 hour file |
|---|---|---|---|
| Browser decode | ~5s | ~30s | ~4min |
| BBC Peaks | ~50ms | ~50ms | ~100ms |
Generating Waveform Data
Install audiowaveform:
# macOS
brew install audiowaveform
# Ubuntu/Debian
sudo apt-get install audiowaveform
# From source
git clone https://github.com/bbc/audiowaveform.git
cd audiowaveform
mkdir build && cd build
cmake .. && make && sudo make install
Generate waveform data:
# Generate from Opus (recommended — always 48000 Hz)
audiowaveform -i audio.opus -o audio.dat -z 256 -b 8
# Generate from MP3 or WAV
audiowaveform -i audio.mp3 -o audio.dat -z 256 -b 8
# Generate 16-bit for higher precision
audiowaveform -i audio.opus -o audio.dat -z 256 -b 16
The -z option sets samples per pixel (zoom level). Lower values = more detail but larger files.
:::caution Sample Rate Matching
Pre-computed peaks embed the source audio's sample rate (e.g., 48000 Hz). The browser's AudioContext decodes audio at its hardware sample rate — typically 48000 Hz on most systems, but 44100 Hz on some devices.
If the rates don't match, the two editors differ. WebAudioProvider keeps the pre-computed peaks: it reads each clip's part of them at the peaks' own rate and scales the zoom by the ratio of the rates, so they fill the clip's box (a clip whose peaks' rate differs from its audio's gets a console warning from createClipFromSeconds once its audio is there, given or loaded). <daw-editor> does not use peaks whose rate differs from its AudioContext's: it warns, ignores the file and draws the waveform from the decoded audio, which waits for the audio to load.
Recommendations:
- Serve audio at 48000 Hz to match most browser AudioContext hardware rates:
- Opus — best compressed option. Always encodes at 48000 Hz (per spec), excellent quality at low bitrates, broad browser support.
ffmpeg -i audio.wav -c:a libopus audio.opus - WAV at 48000 Hz — uncompressed, lossless.
ffmpeg -i audio.wav -ar 48000 audio-48k.wav - FLAC at 48000 Hz — lossless compression (~50-60% of WAV).
ffmpeg -i audio.wav -ar 48000 audio-48k.flac
- Opus — best compressed option. Always encodes at 48000 Hz (per spec), excellent quality at low bitrates, broad browser support.
- Generate
.datfiles from your 48000 Hz audio so peaks match the hardware rate - Set the
sampleRateprop to get an early warning when the hardware rate doesn't match:
// React
<WebAudioProvider sampleRate={48000} arrangement={arrangement} />
// Web Components: the editor's rate is its adapter's AudioContext rate
import { NativePlayoutAdapter } from '@dawcore/transport';
editor.adapter = new NativePlayoutAdapter(new AudioContext({ sampleRate: 48000 }));
When the rates match, pre-computed peaks render at once in both editors. :::
Using Pre-computed Waveforms
Load the peaks first, then add the tracks with the peaks attached, and render the provider once the tracks are in:
import { useEffect, useState } from 'react';
import {
WebAudioProvider,
Waveform,
useCreateArrangement,
loadWaveformData,
} from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
function MyEditor() {
// Starts empty: the track is added once its peaks have loaded (or failed)
const arrangement = useCreateArrangement();
const [peaksSettled, setPeaksSettled] = useState(false);
useEffect(() => {
let cancelled = false;
// 1. Load BBC peaks first (fast - ~50KB). Without them the waveform comes from the audio.
loadWaveformData('/audio/podcast.dat')
.catch(() => undefined)
.then((waveformData) => {
if (cancelled) return;
// An effect run again (StrictMode, Fast Refresh) must not add the track twice
if (arrangement.getTracks().length === 0) {
// 2. The clip names its audio and carries its peaks: drawn at once, playable once decoded
// Not an undo step: no Undo takes the loaded track out
arrangement.addTrack(audioTrack({ src: '/audio/podcast.mp3', name: 'Podcast Episode', waveformData }));
}
setPeaksSettled(true);
});
return () => {
cancelled = true;
};
}, [arrangement]);
if (!peaksSettled) return <div>Loading peaks…</div>;
return (
<WebAudioProvider arrangement={arrangement} sampleRate={48000}>
<Waveform />
</WebAudioProvider>
);
}
The provider is rendered after the track is in because the playlist's ready happens once per mount: a provider mounted over an empty arrangement is ready at once, with no tracks.
When waveformData is provided:
- The library uses BBC peaks instead of computing from audio
- Zoom is supported via
resample()at different samples-per-pixel - Clip trimming (offset/duration) is handled via
slice() - The slice is cut at the peaks' own sample rate, and scaled to the view when that rate differs from the provider's
Waveform Data Format
BBC audiowaveform outputs JSON in this format:
{
"version": 2,
"channels": 2,
"sample_rate": 48000,
"samples_per_pixel": 256,
"bits": 8,
"length": 1000,
"data": [0, 10, -5, 15, ...]
}
The sample_rate field must match the browser's AudioContext.sampleRate for pre-computed peaks to be used. See the sample rate matching note above.
Loading from Different Sources
Remote URLs
audioTrack({ src: 'https://example.com/audio.mp3', name: 'Remote Track' });
The server must allow the cross-origin request (CORS); otherwise the source fails with Failed to fetch ….
Files (Uploads and Drops)
Pass the File itself as src; it is read with file.arrayBuffer(), so no blob URL is needed:
// Named after the file, without its extension. A file the user drops or picks is their edit: one undo step
arrangement.addTrack(audioTrack({ src: file }), { undoable: true });
AudioBuffer (Decoded Already)
Audio you have decoded yourself is an audioBuffer: the clip is loaded at once and nothing is fetched.
async function addDecoded(arrangement: Arrangement, arrayBuffer: ArrayBuffer, audioContext: BaseAudioContext) {
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
arrangement.addTrack(audioTrack({ audioBuffer, name: 'Decoded' }));
}
(Arrangement is a type of @waveform-playlist/engine.)
A Loader of Your Own
useCreateArrangement(init, { loadSource }) replaces how a source becomes an AudioBuffer (by default: fetch a URL or read a Blob, then decode). loadSource(src, { signal, audioContext, stallTimeout }) returns a promise of the buffer; honour signal, which is aborted when the source is no longer wanted or the provider unmounts.
A Load That Takes Too Long
Two limits fail a load that takes too long. Both are options of useCreateArrangement, in milliseconds, read on the first render:
const arrangement = useCreateArrangement(() => tracks, {
sourceStallTimeout: 60_000, // default 30000: no data for this long fails the source
sourceTimeout: 5 * 60_000, // default none: the longest one source may take in all
});
sourceStallTimeout(default 30 seconds) is how long a download may go without receiving data: no response yet, or no new bytes. A download that keeps arriving is never cut off, however large the file or slow the connection. The default loader applies it to a URL; reading aFileand decoding are not timed.sourceTimeout(off by default) is the total time of one load, decoding included, whatever loads it.
A source that runs into a limit is a failed source: useArrangementSources(arrangement) shows it as failed with an Error whose name is 'TimeoutError', and arrangement.retry(src) starts it again with its whole time. Infinity switches a limit off; undefined and null take the default; any other value that is not a number above 0 throws out of the render.
A loadSource of your own is not timed by sourceStallTimeout: it receives the value as stallTimeout in its second argument, which defaultLoadSource applies to a URL when you pass that argument on to it. A fetch your loader makes itself is under no limit unless you time it or set sourceTimeout.
Memory Use of Decoded Audio
WebAudioProvider holds each source whole, as an AudioBuffer: a URL or a file is decoded into one before it plays. A buffer holds 4 bytes per sample per channel at the AudioContext's rate, whatever the file's format or rate: one hour of stereo audio at 48 kHz is about 1.38 GB. The file's size does not predict it: a 39 MB Opus file and a 635 MB WAV of the same hour decode to the same 1.38 GB.
While a file decodes, the page needs more than that. In one set of runs (2026-12-04, macOS, a probe outside this repository that loaded one file with the default loader into a 48 kHz AudioContext, pink noise, Opus 128 kbit/s stereo 48 kHz and WAV 16-bit stereo 44.1 kHz; Chrome 158 and Firefox 160 headless, Safari 27 with a window), the page process grew by the following, at the peak and 5 seconds after the load with the buffer still in use:
| File (size) | Decoded | Chrome: peak / 5 s after | Firefox: peak / 5 s after | Safari: peak / 5 s after |
|---|---|---|---|---|
| 15 min Opus (10 MB) | 346 MB | 1.1 / 0.8 GB | 0.8 / 0.35 GB | 0.7 / 0.7 GB |
| 1 h Opus (39 MB) | 1.38 GB | 3.7–3.9 / 3.0 GB | 3.1 / 1.4 GB | 2.9 / 2.9 GB |
| 3 h Opus (118 MB) | 4.15 GB | 12.7–12.9 / 8.7–8.9 GB | 9.2 / 4.2 GB | 8.7 / 8.7 GB |
| 1 h WAV (635 MB) | 1.38 GB | 5.6 / 3.7–4.4 GB | 3.0–3.1 / 1.4 GB | 6.7 / 6.7 GB |
- The peak is about 3 times the decoded audio in Chrome, about 2.2 times in Firefox and about 2.1 times in Safari, and more for an uncompressed file in Chrome (about 4 times) and Safari (about 4.9 times).
- After the load Firefox held about the decoded buffer, Chrome about twice it, and Safari had released nothing 5 seconds later.
- Every load succeeded, up to 12.9 GB in Chrome. Not run: where a tab runs out of memory, mobile browsers, Windows, Linux, mono audio, other rates.
The library sets no limit and gives no warning for long sources. For long material (a podcast, an audiobook, hours of recording) to be played rather than edited, use MediaElementProvider: it plays one track through an audio element, which streams the file, and decodes nothing up front; its waveform is drawn from pre-computed peaks (waveformData, which it requires).
Supported Formats
Waveform Playlist supports all formats supported by the Web Audio API:
| Format | Extension | Support |
|---|---|---|
| MP3 | .mp3 | All browsers |
| WAV | .wav | All browsers |
| OGG Vorbis | .ogg | Chrome, Firefox, Edge |
| AAC | .m4a, .aac | Safari, Chrome, Edge |
| FLAC | .flac | Chrome, Firefox, Edge |
| WebM | .webm | Chrome, Firefox |
Ready
"Ready" is when the playlist can play. It happens once per mount of the provider: the first time an engine is attached and no source of the arrangement is still pending.
- A source that failed counts as settled: a playlist with a failed file is ready, and the error is in
useArrangementSources. - An empty arrangement is ready as soon as its engine is attached. A file added during the first load extends the wait; one added after the first ready does not bring the playlist back to "not ready".
- A request that hangs is failed by the default loader after 30 seconds without data (A Load That Takes Too Long), and a failed source is settled. A source can still load for ever where the stall limit does not look: a
loadSourceof your own, a download that keeps arriving and never ends (a live stream), a file read or a decode that never finishes, a limit set toInfinity.sourceTimeoutends each of these. Until the playlist is ready Play does nothing, so show the loading state while it lasts:useArrangementSources(arrangement)haspendingCount(sources still loading) andisLoading(pendingCount > 0).
import { useArrangement, useArrangementSources } from '@waveform-playlist/browser';
function LoadingStatus() {
const { pendingCount, isLoading } = useArrangementSources(useArrangement());
return isLoading ? <p>Loading {pendingCount} file(s)…</p> : null;
}
- Play does nothing before the first ready, and nothing is queued: a Play press, Space or an annotation click during the first load does nothing (the annotation is not highlighted either), and in a development build one console warning per mount says so. Edits, the mixer,
seekToand the selection work before ready. play()called fromonReady, or from an effect or layout effect that runs whenisReadyturns true, works.
After the first ready, isReady is false only while a later engine is being built (when effects changes identity or zoomLevels changes content), and true again as soon as that engine is attached, whatever is still loading. onReady and the event are not repeated then, nor after a StrictMode remount or an <Activity> hide and reveal.
A page that has to load something before its tracks exist (MIDI with loadMidiTracks, peaks files) adds the tracks and renders the provider after that, as in Using Pre-computed Waveforms. The tracks it adds are not undo steps, so no clearHistory() is needed.
Custom Event
The provider dispatches webaudio-provider:ready on the window at the first ready:
useEffect(() => {
const handleReady = (event: Event) => {
const { trackCount, duration } = (event as CustomEvent<{ trackCount: number; duration: number }>).detail;
console.log('Playlist ready:', trackCount, 'tracks,', duration, 'seconds of loaded audio');
};
window.addEventListener('webaudio-provider:ready', handleReady);
return () => window.removeEventListener('webaudio-provider:ready', handleReady);
}, []);
trackCount counts every track of the arrangement, loaded or not; duration is the length of the loaded audio, in seconds.
React Hook
Under MediaElementProvider there is no webaudio-provider:ready event, and the hook is useMediaElementTrack().isReady. Under WebAudioProvider, read isReady from useTimeline():
import { useTimeline } from '@waveform-playlist/browser';
function LoadingIndicator() {
const { isReady, tracks } = useTimeline();
if (!isReady) {
return <div>Loading tracks...</div>;
}
return <div>{tracks.length} tracks</div>;
}
Data Attribute (CSS/Testing)
The playlist container has a data-waveform-state attribute, "loading" or "ready", that follows isReady. Under MediaElementProvider it is "ready" from the first render, because the waveform is drawn from pre-computed peaks and does not wait for the player (useMediaElementTrack().isReady says whether the player has loaded):
/* Dim the playlist while loading */
[data-waveform-state="loading"] {
opacity: 0.5;
pointer-events: none;
}
[data-waveform-state="ready"] {
opacity: 1;
}
For E2E tests (Playwright, Cypress):
// Playwright
await page.waitForSelector('[data-waveform-state="ready"]', { timeout: 30000 });
// Cypress
cy.get('[data-waveform-state="ready"]', { timeout: 30000 });
Provider Callback
<WebAudioProvider
arrangement={arrangement}
onReady={() => console.log('Ready to play')}
>
<Waveform />
</WebAudioProvider>
onReady is read when it is called, so an inline arrow builds nothing. If it throws, the provider logs the error and calls onError with it.
Where Errors Land
Each kind of failure reaches a different place:
| What fails | Where it lands |
|---|---|
A file that cannot be fetched or decoded, or whose download stops arriving, or whose load takes longer than sourceTimeout | useArrangementSources(arrangement): the source is failed with its error (for a limit, an Error whose name is 'TimeoutError'). Not onError. Start it again with arrangement.retry(src) |
A track the arrangement refuses, in the useCreateArrangement initializer | A render error, thrown by the component that calls useCreateArrangement: the nearest error boundary above that component catches it |
A track the arrangement refuses, from arrangement.addTrack(), setTracks() or updateTrack() | That call throws: the caller (your handler or effect) catches it. Nothing changed |
| The engine or its adapter cannot be built | The provider's onError, and a console error; the playlist stays in its loading state |
onReady throws | A console error and onError; the playlist is ready all the same |
The arrangement refuses a track whose clips do not match its kind (a clip still loading on a MIDI track included), a duplicate track id, two clips with one id on a track, and a track whose clips overlap (clips that touch are accepted). It checks before changing anything.
import { WaveformErrorBoundary } from '@waveform-playlist/ui-components';
// The boundary wraps the component that calls useCreateArrangement
function MyEditor() {
const arrangement = useCreateArrangement(() => initialTracks);
return (
<WebAudioProvider arrangement={arrangement}>
<Waveform />
</WebAudioProvider>
);
}
<WaveformErrorBoundary fallback={<div>The playlist could not be created.</div>}>
<MyEditor />
</WaveformErrorBoundary>
// A refused track throws at the call
const handleAdd = (track: ArrangementTrack) => {
try {
arrangement.addTrack(track);
} catch (error) {
showMessage(error instanceof Error ? error.message : String(error));
}
};
A Custom Adapter That Closes Its Context
The provider decodes with the AudioContext of its current adapter. A load still in flight when an engine is rebuilt carries on with the previous adapter's context. If your createAdapter returns an adapter whose dispose() closes its AudioContext, such a load can fail; it then shows as failed, and arrangement.retry(src) loads it again with the new context.
Performance Tips
- Use pre-computed waveforms for files over 5 minutes
- Generate peaks at 48000 Hz to match most hardware:
<daw-editor>ignores peaks at another rate and waits for the decoded audio (WebAudioProviderscales them) - Give clips a
duration(or peaks) so they are drawn before their audio has loaded - Compress audio - MP3 loads faster than WAV
- Play long files with
MediaElementProvider, which streams them: a decoded hour of stereo audio takes about 1.38 GB, and two to three times that while it decodes, more for an uncompressed file in Chrome and Safari (Memory Use of Decoded Audio)
Next Steps
- Playback Controls - Control playback
- Track Management - Manage loaded tracks