Hooks
React hooks for accessing playlist state and controls.
Import
import {
// Context hooks: under either provider
useIsPlaying,
useCurrentTime,
useSelection,
useActiveAnnotation,
useAnnotations,
useAnnotationOptions,
usePlaybackControls,
usePlaybackRefs,
useAudioSettings,
useDisplaySettings,
useZoom,
// Context hooks: WebAudioProvider only
useArrangement,
useEditorControls,
useEngineRefs,
useTimeline,
useMixer,
useTrackReorderPreview,
useLoop,
useSelectedTrackId,
useUndoRedo,
useTrack, // inside <WaveformTrackControls> only
useTrackReorderHandle, // inside <WaveformTrackControls> only
// Context hooks: MediaElementProvider only
usePlaybackRate,
useMediaElementTrack,
// Arrangement hooks
useCreateArrangement,
useArrangementTracks,
useArrangementSources,
// Annotation store hooks
useCreateAnnotationStore,
useStoredAnnotations,
// Specialized hooks
useTimeFormat,
// Drag & drop
useClipDragHandlers,
useDragSensors,
// Clip editing
useClipSplitting,
// Keyboard shortcuts
useKeyboardShortcuts,
usePlaybackShortcuts,
// Recording session (with @waveform-playlist/recording)
useRecordingSession,
} from '@waveform-playlist/browser';
// Tone.js batteries-included hooks (import from /tone to keep core bundle engine-free)
import {
useDynamicEffects,
useTrackDynamicEffects,
useExportWav,
useOutputMeter,
} from '@waveform-playlist/browser/tone';
// Recording primitives (lower-level hooks)
import {
useMicrophoneAccess,
useRecording,
useMicrophoneLevel,
useRecordingProgress,
} from '@waveform-playlist/recording';
// Throttled React state from a meter or any other value source
import { useMeterLevels, useThrottledValue } from '@waveform-playlist/ui-components';
Core Context Hooks
These hooks read the nearest playlist provider. Each one returns a group of fields that change together, and a component re-renders only when the value of a hook it calls changes. Call the hook that has the field you need, in the smallest component that needs it.
WebAudioProvider and MediaElementProvider publish what they share through the same hooks, so a component written against the first group below works under either.
Under either provider:
| Hook | Returns | The component re-renders on |
|---|---|---|
useIsPlaying() | isPlaying | play, pause, stop |
useCurrentTime() | currentTime | a seek, a pause, a stop, a selection whose start moves |
useSelection() | selectionStart, selectionEnd | every pointer move of a selection drag |
useActiveAnnotation() | activeAnnotationId, playingAnnotationId | every annotation boundary during playback; a change of the selected annotation |
useAnnotations() | annotations | an annotation edit |
useAnnotationOptions() | editable, linkEndpoints, continuousPlay | one of the three options changing value (a toggle, or a field of the annotationList prop taking a value the option does not have) |
usePlaybackControls() | play, pause, stop, seekTo, setSelection, the annotation store, and the annotation, scroll and time-format setters | a new annotationStore prop; under MediaElementProvider also a track whose waveform data has another sample rate |
usePlaybackRefs() | currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback | never |
useAudioSettings() | sampleRate, mono, indefinitePlayback | a provider prop change |
useDisplaySettings() | timeFormat, isAutomaticScroll | the user changing either setting |
useZoom() | samplesPerPixel, canZoomIn, canZoomOut | a zoom |
WebAudioProvider only:
| Hook | Returns | The component re-renders on |
|---|---|---|
useArrangement() | the provider's Arrangement | never |
useEditorControls() | track mixer and order, zoom, loop, undo, recording | a change of the values of the zoomLevels prop |
useEngineRefs() | playoutRef, the engine's clock refs and functions | never |
useTimeline() | tracks, peaksDataArray, duration, isReady | every clip operation (a trim once, on release), a zoom, audio or peaks arriving, isReady changing |
useMixer() | trackStates, masterVolume | every mute, solo, volume or pan change (also by an undo or a redo); a take starting or ending on a track; tracks added, removed, renamed or reordered |
useTrack() | one track's id, name, mixer state and bound actions. Only among the children of <WaveformTrackControls> | a change of that track's state, position or selection |
useTrackReorderPreview() | trackDragPreview | every drag-over of a track reorder |
useLoop() | isLoopEnabled, loopStart, loopEnd | a loop change |
useSelectedTrackId() | selectedTrackId | another track being selected |
useUndoRedo() | canUndo, canRedo | after an edit |
MediaElementProvider only:
| Hook | Returns | The component re-renders on |
|---|---|---|
usePlaybackRate() | playbackRate, setPlaybackRate | the speed changing |
useMediaElementTrack() | duration, isReady, peaksDataArray, playoutRef | the track or the zoom level changing, the player becoming ready |
A hook of the first group throws outside both providers: useIsPlaying must be used within WebAudioProvider or MediaElementProvider. A hook of the other two groups throws outside its provider, and also when the nearest playlist provider is of the other kind, even if a provider of the right kind is further out: useLoop needs WebAudioProvider, and the nearest playlist provider here is MediaElementProvider, which does not provide it. When providers are nested, every hook reads the nearest one.
The value types (AudioSettingsContextValue and the others named below) are exported from @waveform-playlist/browser, as are ClipPeaks, TrackClipPeaks, TrackDragPreview and FrameData, so every field can be named.
Upgrading? The upgrade guide lists where each field of usePlaylistControls(), usePlaylistAnnotations() and the useMediaElement* hooks went, and an earlier entry does the same for the combined data, state and animation hooks.
useAudioSettings
What the provider was configured with that a view also reads. The value changes on a provider prop change (and once when the real sample rate is known), not on a settings click, and never during an interaction.
function useAudioSettings(): AudioSettingsContextValue;
interface AudioSettingsContextValue {
sampleRate: number;
/**
* Whether tracks are drawn and analysed as one channel. On the provider
* because the provider computes the peaks with it. Always false under the
* MediaElement provider.
*/
mono: boolean;
/**
* Whether playback continues past the end of the audio instead of stopping
* there. On the provider because its animation loop and `seekTo` follow it;
* the multitrack root also draws the timeline as wide as its container
* then. Always false under the MediaElement provider.
*/
indefinitePlayback: boolean;
}
The options that only affect how a view draws (waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport) are not in this value: a leftover read of one is undefined. They are props of <WaveformViewOptions>. A component drawn inside a root reads the values the root resolved with useWaveformViewInfo() from @waveform-playlist/ui-components:
import { useWaveformViewInfo } from '@waveform-playlist/ui-components';
const { waveHeight, barWidth, barGap, roundedBars, progressBarWidth } = useWaveformViewInfo();
// also: sampleRate, samplesPerPixel, timeScaleHeight
Outside a root useWaveformViewInfo() returns its defaults, not the options of a <WaveformViewOptions> above. fillViewport has no reader.
useDisplaySettings
The two settings a user toggles: the time format and automatic scroll. The value changes when the user changes either. They are apart from useAudioSettings() because every clip's progress overlay and the visualization read useAudioSettings(), so a toggle there would re-render all of them. Set them with setTimeFormat(format) and setAutomaticScroll(enabled) from usePlaybackControls().
function useDisplaySettings(): DisplaySettingsContextValue;
interface DisplaySettingsContextValue {
timeFormat: TimeFormat;
isAutomaticScroll: boolean;
}
useZoom
The zoom level. The value changes on a zoom. Under MediaElementProvider the level is its samplesPerPixel prop (followed, no finer than the waveform data): canZoomIn and canZoomOut are always false.
function useZoom(): ZoomContextValue;
interface ZoomContextValue {
samplesPerPixel: number;
canZoomIn: boolean;
canZoomOut: boolean;
}
useTimeline
WebAudioProvider only. What is on the timeline, derived from the provider's arrangement and never written back. The value changes on every clip operation (a trim once, on release: its pointer moves are a preview that only the dragged clip follows), on a zoom (peaksDataArray is computed per zoom level), when audio or peaks arrive for a clip and when isReady changes, so call this hook only in a component that draws tracks or needs the timeline length during render.
function useTimeline(): TimelineContextValue;
interface TimelineContextValue {
/**
* The arrangement's tracks without the clips that are still loading:
* derived from the arrangement, never written back. Change them through
* `useArrangement()`.
*/
tracks: readonly ClipTrack[];
/**
* One row per track, in the order of `tracks`. A row also holds the
* placeholder record (`isPlaceholder: true`) of each clip still loading,
* which `tracks` does not have: find a record by `clipId`, never by position.
*/
peaksDataArray: TrackClipPeaks[];
/** The end, in seconds, of the loaded audio. */
duration: number;
/**
* False until an engine is attached and the first sources have settled;
* then false while a later engine is being built.
*/
isReady: boolean;
}
- One entry per track.
tracks[i],peaksDataArray[i]anduseMixer().trackStates[i]are the same track of the arrangement, also while its audio loads. - Clips: by id, not by position. A clip still loading is not in
tracks[i].clips; when it has adurationorwaveformDataits placeholder record is inpeaksDataArray[i], so the two arrays of a row do not line up. Look a record up byclipId. - Do not write to them. A track whose clips are all loaded is the arrangement's own object (frozen outside production builds); a track that holds a clip still loading is a copy without it. Change tracks through the arrangement.
durationcounts loaded audio only. The view is drawn wide enough for a placeholder that ends later.isReadyis false until the first time an engine is attached and no source of the arrangement is pending (a failed source counts as settled); from then on it is false only while a later engine is being built (aneffectsorzoomLevelschange), whatever is still loading then.play()does nothing until the firsttrue. See Loading Audio.
useMixer
WebAudioProvider only. Mixer state. The value changes on every mute, solo, volume or pan change (each step of a slider drag, and an undo or a redo that moves one), when a take starts or ends on a track, and when tracks are added, removed, renamed or reordered, so call this hook in the component that shows the mixer values, not in the component that renders the page.
function useMixer(): MixerContextValue;
interface MixerContextValue {
trackStates: TrackState[];
masterVolume: number;
}
interface TrackState {
name: string;
/** The track's own mute, or true while a take is recording onto it. */
muted: boolean;
soloed: boolean;
volume: number;
pan: number;
/** The pan law: `'auto'` until the track's first decoded audio decides it. */
panLaw: PanLaw; // 'auto' | 'mono' | 'stereo'
}
trackStates has one entry per track, in the order of useTimeline().tracks: trackStates[i] belongs to tracks[i], and trackStates.length equals tracks.length. Every track has its entry from the moment it enters the arrangement, also while its audio loads; no entry is undefined.
const anySolo = trackStates.some((s) => s.soloed);
The values are the arrangement's mix (arrangement.getMixer()), kept by track id. A track keeps its mute, solo, volume and pan for as long as its id is in the arrangement: when other tracks are removed, when tracks are added in front of it, and when it is reordered. A mixer change is an undo step, so an undo or a redo brings back the values of the state it returns to. While a take is recorded onto a track (setRecordingActive, useRecordingSession), its muted is true: the take plays the track muted, while arrangement.getMixer() holds the track's own mute. A track that enters with an id the arrangement has no mix for starts from its own muted, soloed, volume and pan fields; after that those fields are only the values it entered with, and the current ones are here. The name follows the track's name.
The array keeps its identity while no entry changed (a trim or another clip edit gives new tracks and the same trackStates), and a change to one track replaces the object of that track only.
To change a value, call the setters of useEditorControls() with the track's id. Inside a track's control panel, useTrack() has the values and the setters of that one track.
useTrackReorderPreview
WebAudioProvider only. The live track-reorder drag. The value changes on every drag-over of a track reorder.
function useTrackReorderPreview(): TrackReorderPreviewContextValue;
interface TrackReorderPreviewContextValue {
/** Non-null while a track-reorder drag is live: the dragged track and the
* index it would drop at. Null otherwise. */
trackDragPreview: TrackDragPreview | null;
}
A control panel of your own does not need it: the part positions and lifts the slots itself. Read trackDragPreview to mirror the drag in your own UI, in a panel or outside the view.
useAnnotations
Either provider. The annotations: the list of the provider's annotation store, [] when the provider has none. The value changes on an annotation edit; an edge drag that uses the preview source changes it once, on release. The active annotation is not here: see useActiveAnnotation. The three annotation options are not here either: see useAnnotationOptions. Change the annotations through the store: annotationStore of usePlaybackControls(), or the store your app made.
function useAnnotations(): AnnotationsContextValue;
interface AnnotationsContextValue {
/** The annotation store's list: never write to it (frozen in development). */
annotations: readonly AnnotationData[];
}
useAnnotationOptions
Either provider. The three annotation options: whether annotations can be edited, whether a dragged edge takes the edge it touches along, and whether playback runs on past the end of an annotation. The value changes when one of them is toggled.
function useAnnotationOptions(): AnnotationOptionsContextValue;
interface AnnotationOptionsContextValue {
editable: boolean;
linkEndpoints: boolean;
continuousPlay: boolean;
}
The options are provider state. Each starts from its field of the provider's annotationList prop (editable, linkEndpoints, isContinuousPlay; a field left out is false) and takes the field's new value when that value changes. Set them with setAnnotationsEditable, setLinkEndpoints and setContinuousPlay from usePlaybackControls(), or render <EditableCheckbox />, <LinkEndpointsCheckbox /> and <ContinuousPlayCheckbox /> from @waveform-playlist/annotations. A setter does not change the prop; the prop's next change wins for the field that changed.
useLoop
WebAudioProvider only. The loop region, which is separate from the selection. The value changes on a loop change.
function useLoop(): LoopContextValue;
interface LoopContextValue {
isLoopEnabled: boolean;
loopStart: number;
loopEnd: number;
}
useSelectedTrackId
WebAudioProvider only. The track selected for editing operations. The value changes when another track is selected.
function useSelectedTrackId(): SelectedTrackIdContextValue;
interface SelectedTrackIdContextValue {
selectedTrackId: string | null;
}
useUndoRedo
WebAudioProvider only. Whether undo and redo are available. The value changes after an edit.
function useUndoRedo(): UndoRedoContextValue;
interface UndoRedoContextValue {
canUndo: boolean;
canRedo: boolean;
}
useIsPlaying
Whether playback is running. The value changes on play, pause and stop.
function useIsPlaying(): IsPlayingContextValue;
interface IsPlayingContextValue {
isPlaying: boolean;
}
Example
function StatusBar() {
const { isPlaying } = useIsPlaying();
const { continuousPlay } = useAnnotationOptions();
const { duration } = useTimeline(); // WebAudioProvider only
return (
<div>
<span>{isPlaying ? 'Playing' : 'Stopped'}</span>
<span>Duration: {duration.toFixed(2)}s</span>
<span>Continuous: {continuousPlay ? 'On' : 'Off'}</span>
</div>
);
}
usePlaybackRefs
The playback position refs and the per-frame animation registry. A single requestAnimationFrame loop inside the provider drives all visual updates; components register callbacks instead of spinning their own loops.
The value keeps its identity for the life of the provider, so calling this hook never re-renders the component. Read a ref's .current in an event handler, an effect or a frame callback, not during render. To re-render when the value behind a ref changes, also call the hook that carries it: useCurrentTime() or useIsPlaying().
interface FrameData {
/** Raw engine time (use for state/logic — NOT for visual positioning). */
readonly time: number;
/** engine.getAudibleTime() while playing, raw time when resting. Use for any DOM
* positioning that should match the audible output. */
readonly visualTime: number;
readonly sampleRate: number;
readonly samplesPerPixel: number;
}
function usePlaybackRefs(): PlaybackRefsContextValue;
interface PlaybackRefsContextValue {
/** The playback position, in seconds. Advances during playback. */
currentTimeRef: RefObject<number>;
/**
* The position to DRAW. Under the WebAudio provider it is the audible
* position (the raw time less output latency and lookahead while playing);
* under the MediaElement provider it is `currentTimeRef` itself, because a
* media element reports the audible position.
*/
visualTimeRef: RefObject<number>;
/** Register a per-frame callback driven by the provider's one animation loop. */
registerFrameCallback: (id: string, cb: (data: FrameData) => void) => void;
/** Unregister a per-frame callback. */
unregisterFrameCallback: (id: string) => void;
}
The engine's refs and clock functions (playoutRef, getPlaybackTime and the others) are on useEngineRefs().
Example
Use registerFrameCallback rather than your own requestAnimationFrame loop — it shares the provider's single rAF, runs only while playing, and hands you a fresh FrameData so closure values can't go stale during zoom changes.
function AnimatedPlayhead() {
const { registerFrameCallback, unregisterFrameCallback } = usePlaybackRefs();
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
registerFrameCallback('playhead', ({ visualTime, sampleRate, samplesPerPixel }) => {
if (!ref.current) return;
const pixels = (visualTime * sampleRate) / samplesPerPixel;
ref.current.style.transform = `translateX(${pixels}px)`;
});
return () => unregisterFrameCallback('playhead');
}, [registerFrameCallback, unregisterFrameCallback]);
return <div ref={ref} className="playhead" />;
}
For static positioning when playback is stopped (initial render, after pause/seek), read visualTimeRef.current instead — the loop keeps it current outside of playback too. A component that does so must also call useCurrentTime(), so that it re-renders when the resting position changes.
useEngineRefs
WebAudioProvider only. Refs and functions of the multitrack engine. Like usePlaybackRefs(), the value never changes, so calling this hook never re-renders the component. playoutRef.current is null until the engine is first built and during a rebuild: read it in an event handler, or in an effect that depends on isReady from useTimeline(). The provider owns the selection, the loop, the zoom, the selected track and the master volume and gives them to the engine: change them with the setters of usePlaybackControls() and useEditorControls(). A call on the engine for one of them (playoutRef.current.setSelection(…), .zoomIn()) is not followed by the view.
function useEngineRefs(): EngineRefsContextValue;
interface EngineRefsContextValue {
/** context.currentTime when playback started */
playbackStartTimeRef: RefObject<number>;
/** Audio position when playback started */
audioStartPositionRef: RefObject<number>;
/** Returns raw playback time from engine (auto-wraps at loop boundaries). */
getPlaybackTime: () => number;
/** Current time of the adapter's AudioContext, in seconds. */
getAudioContextTime: () => number;
/** Returns the current adapter scheduler lookahead (Tone ~0.1s, native 0). Use this
* for any audible-latency calculation that must match the playhead. */
getLookAhead: () => number;
/** Returns the adapter AudioContext's output latency in seconds. */
getOutputLatency: () => number;
/** The engine, from @waveform-playlist/engine. `current` is null until the
* first build and during a rebuild. */
playoutRef: RefObject<EditorEngine | null>;
}
usePlaybackRate
MediaElementProvider only. The playback speed and its setter. The value changes when the speed does.
function usePlaybackRate(): PlaybackRateContextValue;
interface PlaybackRateContextValue {
/** The speed `setPlaybackRate` set last (0.5 to 2), or the provider's `playbackRate`
* prop as given (the provider does not clamp it). */
playbackRate: number;
/** Clamped to 0.5–2; NaN is ignored. Stable identity. */
setPlaybackRate: (rate: number) => void;
}
useMediaElementTrack
MediaElementProvider only. The one track of a MediaElement player. The value changes when the track or the zoom level does, and when the player becomes ready.
function useMediaElementTrack(): MediaElementTrackContextValue;
interface MediaElementTrackContextValue {
/** The length of the track's audio, from its waveform data. Never 0 for a real track. */
duration: number;
/** True once the media element has loaded its metadata, false again while a
* replaced player loads. Use this, not `duration`, as "the player can be used". */
isReady: boolean;
/** One track with one clip (`[]` when the peak data could not be read). The clip carries the track's fadeIn / fadeOut. */
peaksDataArray: TrackClipPeaks[];
/** The player. `current` is null until it has been created. */
playoutRef: RefObject<MediaElementPlayout | null>;
}
Arrangement Hooks
An Arrangement (type from @waveform-playlist/engine) owns a multitrack editor's tracks, their mix, the undo history and the loading of the audio the clips name. WebAudioProvider takes one as its arrangement prop and derives everything it publishes from it. These hooks are in the core entry of @waveform-playlist/browser, not in /tone. The arrangement's own methods (addTrack, removeTrack, updateTrack, setTracks, retry, …) are listed in Using the Engine Directly.
useCreateArrangement
function useCreateArrangement(
init?: () => readonly ArrangementTrack[],
options?: UseCreateArrangementOptions
): Arrangement;
interface UseCreateArrangementOptions {
loadSource?: LoadSource; // how a clip's source is fetched and decoded
undoLimit?: number; // how many undo steps the arrangement keeps (default 100)
sourceTimeout?: number; // ms; the total time one load may take. Default: no limit (Infinity)
sourceStallTimeout?: number; // ms; how long a load may receive no data. Default 30000; Infinity: no limit
}
Makes one Arrangement per component instance and returns the same one on every render. init and options are read on the first render only; a later render with other values changes nothing. Only loadSource, undoLimit, sourceTimeout and sourceStallTimeout are read from the options. The two limits are described in Loading Audio; one that is neither undefined nor null and is not a number above 0 throws out of the render. The tracks the initializer returns are not an undo step.
import { WebAudioProvider, Waveform, useCreateArrangement } from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
function Editor() {
const arrangement = useCreateArrangement(() => [
audioTrack({ name: 'Drums', src: '/audio/drums.mp3' }),
audioTrack({ name: 'Bass', src: '/audio/bass.mp3', start: 4 }),
]);
return (
<WebAudioProvider arrangement={arrangement}>
<Waveform />
</WebAudioProvider>
);
}
An initializer that throws (a track of the wrong kind, a clip still loading on a MIDI track, a duplicate track id, two clips with one id on a track, clips on a track that overlap) throws out of the render, so it lands in the nearest error boundary above the component that calls the hook, not in a provider's onError. Under StrictMode the initializer runs twice and one result is kept.
Creating an arrangement fetches nothing. A loading clip's source is fetched and decoded once a decode context is attached: WebAudioProvider attaches its adapter's AudioContext when its first adapter exists, and takes it away again when it unmounts.
useArrangement
function useArrangement(): Arrangement;
The arrangement of the nearest WebAudioProvider, for a component below it that changes the tracks. The value never changes for a mount of the provider, so calling this hook never re-renders the component. It throws outside a provider and when the nearest playlist provider is a MediaElementProvider.
import { useArrangement } from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
function AddFileButton() {
const arrangement = useArrangement();
return (
<input
type="file"
accept="audio/*"
onChange={(e) => {
const file = e.target.files?.[0];
// The user's pick: one undo step (an add without the option is none)
if (file) arrangement.addTrack(audioTrack({ src: file }), { undoable: true });
}}
/>
);
}
useArrangementTracks
function useArrangementTracks(arrangement: Arrangement): readonly ArrangementTrack[];
Returns arrangement.getTracks(), loading clips included (narrow a clip with isLoadingClip from @waveform-playlist/core). useTimeline().tracks is the same tracks without the clips still loading. The component re-renders when the tracks change, not when the mix changes (a volume, mute, solo or pan). Do not write to what it returns. The argument is required, so the hook also works above the provider.
useArrangementSources
function useArrangementSources(arrangement: Arrangement): ArrangementSourcesValue;
interface ArrangementSourcesValue {
sources: ReadonlyMap<ClipSource, ArrangementSourceState>; // the order of the entries means nothing
pendingCount: number;
failedCount: number;
isLoading: boolean; // true while a source is pending
}
interface ArrangementSourceState {
status: 'pending' | 'loaded' | 'failed';
error?: Error; // only on a failed source
}
Where each source the arrangement's clips name is. It is the same object until a status changes or a source is added or dropped. The argument is required. A failed source is reported here and nowhere else: it does not call the provider's onError. arrangement.retry(src) starts a failed source again.
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}>
{state.error?.message}{' '}
<button type="button" onClick={() => arrangement.retry(src)}>
Retry
</button>
</span>
))}
</div>
);
}
useAudioTracks and useDynamicTracks are removed: a track names its audio with audioTrack({ src }) in the arrangement, which loads it. See the upgrade guide.
Annotation Store Hooks
An AnnotationStore (type from @waveform-playlist/core) owns the annotations. Both providers take one as their annotationStore prop, publish what it holds and write nothing back; every change, the library's and yours, is a call to its set(list), update(fn) or rename(from, to). These hooks are in the core entry of @waveform-playlist/browser. The store itself, beforeChange, what it refuses and how to save the annotations are in the Annotations guide.
useCreateAnnotationStore
function useCreateAnnotationStore(
init?: () => readonly AnnotationData[],
options?: AnnotationStoreOptions
): AnnotationStore;
interface AnnotationStoreOptions {
/** Returns the list to store: `next` to accept, `current` to refuse, another list to adjust. */
beforeChange?: (
next: readonly AnnotationData[],
current: readonly AnnotationData[]
) => readonly AnnotationData[];
}
Makes one store per component instance and returns the same one on every render. init is read on the first render only. An initializer whose list the store refuses (an annotation without finite numeric start and end, two annotations with one id) throws out of the render, to the nearest error boundary above the component that calls the hook. Under StrictMode the initializer runs twice and one result is kept.
options.beforeChange is followed: the store calls the function passed on the most recent committed render, so a rule that reads your component's state sees its current value. It is not called for the initial list.
import {
WebAudioProvider,
Waveform,
useCreateAnnotationStore,
} from '@waveform-playlist/browser';
import { AnnotationProvider } from '@waveform-playlist/annotations';
function Editor({ arrangement, initialAnnotations }) {
const annotationStore = useCreateAnnotationStore(() => initialAnnotations);
return (
<WebAudioProvider
arrangement={arrangement}
annotationStore={annotationStore}
annotationList={{ editable: true }}
>
<AnnotationProvider>
<Waveform />
</AnnotationProvider>
</WebAudioProvider>
);
}
createAnnotationStore(initial?, options?) from @waveform-playlist/core makes a store without React.
useStoredAnnotations
function useStoredAnnotations(store: AnnotationStore): readonly AnnotationData[];
The store's list, for your own components; the component re-renders when it changes. The argument is required, so the hook works above the provider as well as below it. It is the same array until the annotations change. Do not write to it: in a development build (process.env.NODE_ENV is not 'production', unset included; a page with no process at all freezes nothing) it is frozen, and a write in place throws (.sort() in any code, a field assignment in strict code). Change the annotations with store.set or store.update.
import { useEffect } from 'react';
import { useStoredAnnotations } from '@waveform-playlist/browser';
function SaveAnnotations({ store }) {
const annotations = useStoredAnnotations(store);
useEffect(() => {
localStorage.setItem('annotations', JSON.stringify(annotations));
}, [annotations]);
return null;
}
useSelection
The selected time range, in seconds. It has its own context because it changes on every pointer move of a selection drag; a component that calls this hook re-renders that often, and components that do not call it are not re-rendered by the drag.
Signature
function useSelection(): SelectionContextValue;
Returns
interface SelectionContextValue {
/** Equal to `selectionEnd` when nothing is selected */
selectionStart: number;
selectionEnd: number;
}
Example
function SelectionReadout() {
const { selectionStart, selectionEnd } = useSelection();
const { setSelection } = usePlaybackControls();
if (selectionStart === selectionEnd) return <span>No selection</span>;
return (
<span>
{selectionStart.toFixed(2)}s to {selectionEnd.toFixed(2)}s{' '}
<button onClick={() => setSelection(0, 0)}>Clear</button>
</span>
);
}
Available under either provider.
useCurrentTime
Where the cursor rests, in seconds: the position playback starts from. It changes on a seek (seekTo; under WebAudioProvider also setCurrentTime), a pause, a stop (including playback reaching the end) and a selection whose start moves. It does not advance during playback; for a live position read currentTimeRef or register a frame callback, both from usePlaybackRefs().
It has its own context so that a component reading isPlaying (useIsPlaying()) or a ref (usePlaybackRefs()) is not re-rendered by every seek, nor by every pointer move of a selection drag to the left.
Signature
function useCurrentTime(): CurrentTimeContextValue;
Returns
interface CurrentTimeContextValue {
/** Where the cursor rests, in seconds. Does not advance during playback. */
currentTime: number;
}
Example
function CursorReadout() {
const { currentTime } = useCurrentTime();
return <span>Cursor at {currentTime.toFixed(2)}s</span>;
}
Available under either provider.
useActiveAnnotation
Two ids, each null when there is none: the selected annotation and the playing one. They have their own context because the playing one changes at every annotation boundary during playback; a component that calls this hook re-renders that often, and components that only call useAnnotations() do not.
Signature
function useActiveAnnotation(): ActiveAnnotationContextValue;
Returns
interface ActiveAnnotationContextValue {
/**
* The selection: the annotation the user chose (a click, a selection key)
* or the app set (`setActiveAnnotationId`). Playback never changes it, and
* neither does Stop. It names an annotation the store holds: `null` once
* that annotation leaves the store, and the new id after the store's
* `rename`. The same meaning as `activeAnnotationId` of
* `<daw-annotation-track>`.
*/
activeAnnotationId: string | null;
/**
* The annotation the playhead is in while playing (`start <= time < end`),
* `null` in a gap. Kept on pause, `null` once playback stops. Read-only:
* playback is its only writer.
*/
playingAnnotationId: string | null;
}
activeAnnotationId (the selection) | playingAnnotationId | |
|---|---|---|
| Written by | a click on a box or a list row (playAnnotation), the selection keys of <KeyboardShortcuts annotations>, setActiveAnnotationId(id) from usePlaybackControls() | playback only; there is no setter |
| During playback | does not change | follows the playhead: the annotation it is in (with annotations that overlap, the first one in list order), null in a gap |
| Pause | kept | kept |
| Stop, the end of the audio or the timeline, a play that reaches its own end | kept | null |
seekTo, setSelection | kept | follows the playhead while playing |
New audio under MediaElementProvider (another source or waveformData) | null | null |
The selected annotation leaves the store (removed, its id changed by set or update, another store) | null | not changed |
The store's rename(from, to) of the selected annotation | the new id | not changed |
setActiveAnnotationId(id) with an id the store does not hold when the provider renders | not changed (a warning in development) | not changed |
The built-in boxes and list rows draw both: the selected look for the selected annotation, a lighter look for the playing one when it is not the selected one, and aria-current="true" on the playing one. See Styling for the theme keys.
Example
function NowPlaying() {
const { annotations } = useAnnotations();
const { playingAnnotationId } = useActiveAnnotation();
const playing = annotations.find((a) => a.id === playingAnnotationId);
return playing ? <p>{playing.lines.join(' ')}</p> : null;
}
Available under either provider.
usePlaybackControls
The actions both providers have. The value changes only when the provider is given another annotationStore, and under MediaElementProvider also when the sample rate of the track's waveform data changes, so calling this hook does not re-render the component otherwise.
Signature
function usePlaybackControls(): PlaybackControlsContextValue;
Returns
interface PlaybackControlsContextValue {
/**
* Starts playback at `startTime` (default: the cursor). With `playDuration`
* it stops by itself after that many seconds of audio.
*/
play: (startTime?: number, playDuration?: number) => Promise<void>;
pause: () => void;
/** Ends playback and returns the cursor to where playback started. */
stop: () => void;
/** Moves the cursor, held between 0 and the end of the audio. Under WebAudioProvider a
* finite time past the end is kept with `indefinitePlayback` or during a recording
* session. During playback, playback restarts there. */
seekTo: (time: number) => void;
/** Sets the selected range and moves the cursor to its start. The two times may come in
* either order (the smaller is the start), and each is held at 0 or later; under
* MediaElementProvider also at the length of the audio. A call with a time that is
* NaN changes nothing. During playback, playback
* restarts: a range is played start to end (open-ended under WebAudioProvider with
* looping on), a collapsed one carries on from there. */
setSelection: (start: number, end: number) => void;
setTimeFormat: (format: TimeFormat) => void;
setAutomaticScroll: (enabled: boolean) => void;
setScrollContainer: (element: HTMLDivElement | null) => void;
scrollContainerRef: RefObject<HTMLDivElement | null>;
setContinuousPlay: (enabled: boolean) => void;
setAnnotationsEditable: (enabled: boolean) => void;
setLinkEndpoints: (enabled: boolean) => void;
/**
* Where an annotation edge drag shows its moves while it is in progress.
* Pass it to `useAnnotationDragHandlers({ preview })`; read it in a custom
* annotation renderer with `useAnnotationsWithPreview`. Stable identity.
*/
annotationPreview: AnnotationPreviewHandle;
/**
* The provider's `annotationStore` prop, or `undefined` without one: the
* owner of the annotations. Change them with its `set`, `update` and `rename`. Its
* identity changes only when the prop does.
*/
annotationStore: AnnotationStore | undefined;
/**
* Select an annotation, or `null` for none. Judged when the provider
* renders: a call in the same batch as the `set` that adds the id works,
* and an id the store does not hold is ignored, as if the call had not been
* made (a warning in development).
*/
setActiveAnnotationId: (id: string | null) => void;
/**
* What a click on an annotation does (its box, or its row in the list): the
* annotation becomes the selected one and is played from its start. With
* continuous play off, playback ends where the annotation ends: this is
* the only play an annotation's end cuts. Call it
* from a box or a row of your own. Each provider plays an annotation its
* own way: `WebAudioProvider` starts a play of the annotation's
* length, `MediaElementProvider` starts an open-ended play that its
* loop ends with that annotation. Left alone, both end at the
* annotation's end, also when the play is paused and resumed with
* `play()`; a Stop, a seek or a cursor move ends the play of the
* annotation, and what plays after it is not cut. They differ when something changes during the play:
* under MediaElement the play follows an end that is moved, and continuous
* play switched on lets it run on; under WebAudio the first keeps the end
* it started with. A start that fails is logged as a warning.
*/
playAnnotation: (annotation: AnnotationData) => void;
}
Example
function CustomControls() {
const { play, pause, stop, seekTo } = usePlaybackControls();
return (
<div>
<button onClick={() => play()}>Play</button>
<button onClick={() => pause()}>Pause</button>
<button onClick={() => stop()}>Stop</button>
<button onClick={() => seekTo(0)}>Go to Start</button>
</div>
);
}
useEditorControls
The actions only the multitrack editor has. WebAudioProvider only. The value changes only when the values of the provider's zoomLevels prop change (zoomIn and zoomOut step through them).
Signature
function useEditorControls(): EditorControlsContextValue;
Returns
interface EditorControlsContextValue {
/** Moves the cursor without touching playback. `seekTo` is the one to use
* from a control; this is for the view's own press and drag handling. */
setCurrentTime: (time: number) => void;
// Track mixer, by track id. An id no track has is ignored. They change the
// arrangement's mix, also while no engine is attached. Each call is an undo
// step of the arrangement; `options` (`MixerChangeOptions` from
// `@waveform-playlist/engine`) makes calls with one `gesture` id one step,
// or a value with `undoable: false` no step. Inside a track's control
// panel, `useTrack()` has the same actions already bound to that track.
setTrackMute: (trackId: string, muted: boolean, options?: MixerChangeOptions) => void;
setTrackSolo: (trackId: string, soloed: boolean, options?: MixerChangeOptions) => void;
/** Finite and 0 or more (above 1 boosts). A non-number or a non-finite value throws a TypeError, a negative one a RangeError, before anything changes. */
setTrackVolume: (trackId: string, volume: number, options?: MixerChangeOptions) => void;
/** Finite, from -1 to 1. A non-number or a non-finite value throws a TypeError, one outside the range a RangeError, before anything changes. */
setTrackPan: (trackId: string, pan: number, options?: MixerChangeOptions) => void;
/** `'mono'` or `'stereo'`; any other value, `'auto'` included, throws a `TypeError`. */
setTrackPanLaw: (trackId: string, panLaw: 'mono' | 'stereo', options?: MixerChangeOptions) => void;
/** Move a track to a new index in the vertical track order. Purely
* organizational — playback is not interrupted. An undo step of the
* arrangement. `toIndex` is an integer: one outside the order is the
* first or the last place, anything else throws a `TypeError`. */
reorderTrack: (trackId: string, toIndex: number) => void;
/** Internal wiring for ClipInteractionProvider: publishes/clears the live
* track-reorder drag preview. */
setTrackDragPreview: Dispatch<SetStateAction<TrackDragPreview | null>>;
setSelectedTrackId: (trackId: string | null) => void;
// Zoom
zoomIn: () => void;
zoomOut: () => void;
// Master volume
/** Finite and 0 or more (above 1 boosts). A non-number or a non-finite value throws a TypeError, a negative one a RangeError, before anything changes. */
setMasterVolume: (volume: number) => void;
// Loop controls
setLoopEnabled: (enabled: boolean) => void;
setLoopRegion: (start: number, end: number) => void;
setLoopRegionFromSelection: () => void;
clearLoopRegion: () => void;
// Undo/redo: the arrangement's history, engine or not. Both do nothing while
// a clip move, a clip trim or a track-reorder drag is in progress (#848).
undo: () => void;
redo: () => void;
// Recording
/** Mark a recording session active/inactive. While active: (1) the
* end-of-audio auto-stop is suppressed so overdub playback runs past the
* end of existing material, and (2) with a `recordingTrackId`, that track
* is marked in the arrangement as the one the take is recording onto
* (`setTrackRecording`): punch-in recording replaces whatever the take
* overlaps, so the doomed material must not play under the overdub. The
* take's mute plays the track muted and is no undo step. `trackStates`
* and the track's Mute button show it muted, the built-in
* `<TrackMuteButton />` of that track is disabled, and
* `useTrack().isRecording` is true for it, while
* `arrangement.getMixer()` keeps the track's own mute: nothing is written
* to it, so a mute changed during the take stays after it. One track is
* recorded onto at a time: naming one clears any other, and
* `setRecordingActive(false)` clears every track. `useRecordingSession`
* calls it for the length of a take; overdub flows should also call it
* eagerly (before `play()`). */
setRecordingActive: (active: boolean, recordingTrackId?: string | null) => void;
}
The four mixer setters take the track's id (they took its index before; see the upgrade guide). A first argument that is not a string is ignored, and in development each setter says so once in the console. A string that is no track's id is ignored without a message.
The mixer setters, reorderTrack, undo and redo call the provider's arrangement, so they work before the first engine is built and while an engine is rebuilt; the next engine plays what they changed. A value set while a track's audio is still loading is kept. undo and redo do nothing while a clip move, a clip trim or a track-reorder drag is in progress (an undo in the middle of a drag would land the clip away from the pointer); the drag does not change canUndo / canRedo, so an Undo button stays enabled and pressing it does nothing (#848).
Each mixer call is an undo step, and an undo, a redo or an aborted transaction brings back the mix of the state it returns to: Undo after a fader move moves the fader back. A slider that calls a setter on every move makes one step per move unless it passes one gesture id for the whole drag; the built-in <TrackVolumeSlider /> and <TrackPanSlider /> do, so a drag, or a held arrow key, is one step. For a slider of your own, make one createMixerGesture() (from @waveform-playlist/core) per slider, attach it to the input and pass { gesture: gesture.id } (see the upgrade guide). A value that is not the user's edit, such as automation or a mix restored from a saved project, takes { undoable: false }: no step, and no undo or redo brings back an older value. Keyboard Undo (<KeyboardShortcuts undo />) does not fire while a slider has focus, which it keeps after a mouse drag (#730); an Undo button, or the key once focus has left the slider, works.
If the provider unmounts (or is hidden by <Activity>) while a take is recording onto a track, the take's mute is cleared then too.
const { tracks } = useTimeline();
const { setTrackMute, setTrackVolume } = useEditorControls();
setTrackMute(tracks[0].id, true);
tracks.forEach((track) => setTrackVolume(track.id, 0.8));
useTrack
The track whose control panel the calling component is part of. WebAudioProvider only, and only among the children of <WaveformTrackControls>, which renders its children once per track, each copy inside that track's context. The built-in pieces (<TrackMuteButton /> and the others) are components that call this hook.
Signature
function useTrack(): TrackContextValue;
Returns
interface TrackContextValue {
/** The track's id. */
id: string;
/** `'audio'` or `'midi'`. */
kind: TrackKind;
/** The track's position in the list of tracks, from 0. Changes on a reorder. */
index: number;
/** The track's name, or "Track N" (N is the position, from 1) when it has none. */
name: string;
/** The track's own mute, or true while a take is recording onto it (`isRecording`). */
muted: boolean;
soloed: boolean;
/** Linear gain, 0 or more (the built-in slider sets 0 to 1). */
volume: number;
/** -1 (left) to 1 (right). */
pan: number;
/** The pan law: `'auto'` until the track's first decoded audio decides it. */
panLaw: PanLaw;
/** How the track is drawn. Always `'waveform'` for a MIDI track. */
renderMode: RenderMode;
/** Whether this is the selected track. */
isSelected: boolean;
isFirst: boolean;
isLast: boolean;
/**
* True for an audio track under a `<SpectrogramProvider>`: `setRenderMode`
* and `openSpectrogramSettings` then do something.
*/
hasSpectrogram: boolean;
/**
* True while a take is being recorded onto this track (`setRecordingActive`,
* `useRecordingSession`). The track plays muted for the take and `muted` is
* true, while the track's own mute (`arrangement.getMixer()`) is not
* changed by the take: a mute set meanwhile stays after it. The built-in
* `<TrackMuteButton />` is disabled while this is true; an app's own mute
* control can do the same, since toggling from `muted` here would set the
* track's own mute from the take's mute.
*/
isRecording: boolean;
// Actions. Each keeps its identity while the track's slot is mounted and a
// track menu neither becomes available nor stops being so. The four mixer
// actions are undo steps; `options` (`MixerChangeOptions` from
// `@waveform-playlist/engine`) makes calls with one `gesture` id one step,
// or a value with `undoable: false` no step.
setMuted: (muted: boolean, options?: MixerChangeOptions) => void;
setSoloed: (soloed: boolean, options?: MixerChangeOptions) => void;
/** Finite and 0 or more (above 1 boosts). A non-number or a non-finite value throws a TypeError, a negative one a RangeError, before anything changes. */
setVolume: (volume: number, options?: MixerChangeOptions) => void;
/** Finite, from -1 to 1. A non-number or a non-finite value throws a TypeError, one outside the range a RangeError, before anything changes. */
setPan: (pan: number, options?: MixerChangeOptions) => void;
/** `'mono'` or `'stereo'`; any other value throws a `TypeError`. Nothing happens for a MIDI track. */
setPanLaw: (panLaw: 'mono' | 'stereo', options?: MixerChangeOptions) => void;
/** Makes this the selected track. */
select: () => void;
/** Moves the track one position up. Nothing happens for the first track. */
moveUp: () => void;
/** Moves the track one position down. Nothing happens for the last track. */
moveDown: () => void;
/**
* Sets the track's `renderMode` in the arrangement: an undo step. The mode
* the track is already drawn with (an unset one is `'waveform'`) changes
* nothing, and so does any mode for a MIDI track. Nothing happens without a
* `<SpectrogramProvider>`.
*/
setRenderMode: (mode: RenderMode) => void;
/** Opens the spectrogram settings of this track. Nothing happens without a `<SpectrogramProvider>`. */
openSpectrogramSettings: () => void;
}
The values are the arrangement's mix for this track, also while its audio is still loading, and the actions work then: a value set while the track loads is kept. Each mixer action is an undo step, as for the setters of useEditorControls(); a slider of your own passes one gesture id per drag, as in the example below. The built-in pieces are enabled while a track loads. isLoading is removed (a leftover read is undefined); to show loading, read useArrangementSources(useArrangement()).
The value changes when something about this track changes: its mixer state, its position (a reorder, or a track removed above it), whether it is selected, its render mode, whether a take is being recorded onto it. A volume step on one track renders the components that call useTrack() in that track's panel and in no other. Selecting a track renders them in two panels: the one that stops being selected and the one that becomes selected.
No reorder remounts a slot, whether by drag or by the move buttons: React state held inside a panel survives it.
Example
import { useEffect, useRef, useState } from 'react';
import { WaveformTrackControls, useTrack } from '@waveform-playlist/browser';
import { createMixerGesture } from '@waveform-playlist/core';
function TrackStrip() {
const { name, muted, volume, isRecording, setMuted, setVolume } = useTrack();
// One gesture helper per slider: a drag, or a held arrow key, is one undo step.
const [gesture] = useState(createMixerGesture);
const sliderRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const input = sliderRef.current;
return input ? gesture.attach(input) : undefined;
}, [gesture]);
return (
<div style={{ height: '100%', padding: 8, boxSizing: 'border-box' }}>
<strong>{name}</strong>
{/* Pressed during a take: a click would set the track's own mute from it */}
<button disabled={isRecording} aria-pressed={muted} onClick={() => setMuted(!muted)}>
Mute
</button>
<input
ref={sliderRef}
type="range"
min="0"
max="1"
step="0.01"
value={volume}
aria-label="Volume"
onChange={(e) => setVolume(parseFloat(e.target.value), { gesture: gesture.id })}
/>
</div>
);
}
<WaveformTrackControls width={180}>
<TrackStrip />
</WaveformTrackControls>
Where it throws
Outside the children of <WaveformTrackControls> the hook throws useTrack must be used within <WaveformTrackControls>…. That is the case for a mixer strip elsewhere on the page: there, read useMixer().trackStates and call the setters of useEditorControls() with a track id. It is also the case everywhere under MediaElementProvider, which has one track and no mixer (those two hooks throw there as well). A scope that makes the pieces work outside the part is tracked in #797.
useTrackReorderHandle
Makes the track whose control panel the caller is part of draggable by an element of your own, to reorder the tracks. <TrackReorderGrip /> is this hook with the built-in grip. Only among the children of <WaveformTrackControls>, and the drag needs a ClipInteractionProvider above the view.
Signature
function useTrackReorderHandle(): TrackReorderHandle;
interface TrackReorderHandle {
/** Attach to the element the track is dragged by (a grip). */
handleRef: (element: Element | null) => void;
/** True while this track is the one being dragged. */
isDragSource: boolean;
}
Example
function MyGrip() {
const { handleRef, isDragSource } = useTrackReorderHandle();
return (
<button
ref={handleRef}
aria-label="Drag to reorder"
onClick={(e) => e.stopPropagation()}
style={{ cursor: isDragSource ? 'grabbing' : 'grab' }}
>
⠿
</button>
);
}
<WaveformTrackControls>
<DefaultTrackControls />
<MyGrip />
</WaveformTrackControls>
- The element that moves is the slot
<WaveformTrackControls>draws around the panel, not an element of yours. The part draws it lifted (opaque, with a shadow) while it is dragged. - The drag is vertical only and skips clip collision and snapping.
- Call it once per panel: two calls for one track register the same item twice. So not together with
<TrackReorderGrip />. <MyGrip />above is written beside the default panel, where it is outside the visible slot unless it positions itself (position: absolute); or put it inside your own panel.- For move buttons,
useTrack()hasmoveUp,moveDown,isFirstandisLast.
useTimeFormat
Control time format display.
Signature
import type { TimeFormat } from '@waveform-playlist/ui-components';
function useTimeFormat(): {
timeFormat: TimeFormat; // starts as 'hh:mm:ss.uuu'
setTimeFormat: (format: TimeFormat) => void;
formatTime: (seconds: number) => string;
/** Seconds, or `null` when the text is not a time in the current format. */
parseTime: (timeString: string) => number | null;
};
The hook keeps its own format state; it is not the provider's time format (read that with useDisplaySettings().timeFormat).
Available Formats
What formatTime(123.456) returns in each format. A negative, NaN or infinite time prints as zero in the format (0, 0.000, 00:00:00.000), and hours do not wrap at 24.
| Format | Example |
|---|---|
seconds | 123 |
thousandths | 123.456 |
hh:mm:ss | 00:02:03 |
hh:mm:ss.u | 00:02:03.5 |
hh:mm:ss.uu | 00:02:03.46 |
hh:mm:ss.uuu | 00:02:03.456 |
parseTime reads a plain number in seconds and thousandths. In the clock formats it also reads 1.5 (seconds) and 1:30 (minutes and seconds) besides 00:02:03.456. It returns null for empty text, letters, a negative number, a number followed by other text, and minutes or seconds of 60 or more after a larger part.
Example
import type { TimeFormat } from '@waveform-playlist/ui-components';
function TimeDisplay() {
// The resting cursor position; it does not advance during playback
const { currentTime } = useCurrentTime();
const { formatTime, setTimeFormat } = useTimeFormat();
return (
<div>
<span>{formatTime(currentTime)}</span>
<select onChange={(e) => setTimeFormat(e.target.value as TimeFormat)}>
<option value="thousandths">0.000</option>
<option value="hh:mm:ss">00:00:00</option>
<option value="seconds">Seconds</option>
</select>
</div>
);
}
Integrated Recording
useIntegratedRecording
From @waveform-playlist/recording
Full-featured recording hook that integrates with the playlist: microphone access, recording, live peaks, and the take added to the arrangement.
function useIntegratedRecording(
arrangement: Arrangement, // the owner of the tracks (useCreateArrangement)
selectedTrackId: string | null, // the track the next take is recorded onto
options?: IntegratedRecordingOptions
): UseIntegratedRecordingReturn;
The hook keeps no copy of the tracks: it reads the arrangement when a take starts and when it ends. At the end it adds the take to the track it was started on with one arrangement.updateTrack(), so a take, together with the clips it trims, removes or splits (punch-in), is one undo step.
startRecording() resolves false, records nothing and sets error when no track is selected, when the arrangement holds no track of the selected id, for a MIDI track, and for a track that holds a clip whose audio is not loaded (still loading, failed to load, or a clip that cannot be made from its audio). Each message starts with Cannot start recording: and names the track, for example Cannot start recording: the selected track "t1" is not in the arrangement. Add it with arrangement.addTrack() first. At the end of a take, a track that is gone (Recording completed but track "t1" no longer exists. The recorded audio could not be saved.) or one the arrangement refuses the take on (Recording completed but the take could not be saved on track "t1": …, with the arrangement's error as cause) sets error and keeps nothing.
Options
interface IntegratedRecordingOptions {
currentTime?: number; // Current playhead position for recording start
audioConstraints?: MediaTrackConstraints; // Override recording-optimized defaults
channelCount?: number; // Default: 1 (auto-detected from stream; fallback)
samplesPerPixel?: number; // Default: 1024
latencyOffset?: number; // Seconds skipped at the start; omitted: auto (outputLatency + lookAhead)
}
Returns
interface UseIntegratedRecordingReturn {
// Recording state
isRecording: boolean;
isPaused: boolean;
// The track the running take will be added to (the one selected when
// startRecording() was called); null whenever isRecording is false.
recordingTrackId: string | null;
// Live microphone levels: { levels, peakLevels, rmsLevels } per channel (0-1).
// A source, not state: the hook does not re-render as levels change.
meter: MeterSource;
// Elapsed time and live-preview peaks of the take: { duration, peaks }.
// A source, not state. Pass it to <WaveformRecordingPreview recordingState={{ …, progress }} />.
progress: RecordingProgressSource;
// Device management
// The open microphone; null while none is open (stream !== null: one is open).
stream: MediaStream | null;
devices: MicrophoneDevice[];
// devices names the real microphones (false before a first grant). When it is
// true before one is open (Chromium holding the permission), a picker can
// offer them and changeDevice(id) opens only that one.
hasLabels: boolean;
// The open microphone, read from the stream (getSettings().deviceId);
// null while none is open or opening. Chromium reported 'default' for the
// default one.
selectedDevice: string | null;
// Controls
/** Resolves true when the capture pipeline actually started; false (and sets error)
* when the take is refused. */
startRecording: () => Promise<boolean>;
/** Stops the take and adds it to the track it was started on: one undo step.
* A take that ends by itself (microphone unplugged, component hidden or
* unmounted mid-take) is added the same way. */
stopRecording: () => Promise<void>;
pauseRecording: () => void;
resumeRecording: () => void;
requestMicAccess: () => Promise<void>;
changeDevice: (deviceId: string) => Promise<void>;
// Error handling
error: Error | null;
}
meter and progress keep the same identity for the life of the hook. See Value sources for how to read them.
Example
import { useArrangement, useCurrentTime, useSelectedTrackId } from '@waveform-playlist/browser';
import { useIntegratedRecording, useRecordingProgress } from '@waveform-playlist/recording';
import { SegmentedVUMeter } from '@waveform-playlist/ui-components';
import type { RecordingProgressSource } from '@waveform-playlist/core';
// Rendered inside <WebAudioProvider arrangement={arrangement}>
function RecordingControls() {
const arrangement = useArrangement();
const { selectedTrackId } = useSelectedTrackId();
const { currentTime } = useCurrentTime();
const {
isRecording,
meter,
progress,
devices,
hasLabels,
stream,
selectedDevice,
startRecording,
stopRecording,
requestMicAccess,
changeDevice,
error,
} = useIntegratedRecording(arrangement, selectedTrackId, { currentTime });
// Before a first grant the browser names no device: open the default one.
if (!stream && !hasLabels) {
return <button onClick={requestMicAccess}>Enable Microphone</button>;
}
// A <select> whose value matches no option would show its first device.
const listed = devices.some((d) => d.deviceId === selectedDevice);
return (
<div>
{/* Shows the open microphone when the list has it; choosing one opens only that one. */}
<select value={(listed && selectedDevice) || ''} onChange={(e) => changeDevice(e.target.value)}>
{!listed && <option value="" disabled>Choose a microphone</option>}
{devices.map(d => <option key={d.deviceId} value={d.deviceId}>{d.label}</option>)}
</select>
<button onClick={isRecording ? stopRecording : startRecording}>
{isRecording ? 'Stop' : 'Record'}
</button>
{isRecording && <ElapsedTime progress={progress} />}
<SegmentedVUMeter meter={meter} />
</div>
);
}
// Only this small component re-renders as the take grows (10 times a second).
function ElapsedTime({ progress }: { progress: RecordingProgressSource }) {
const { duration } = useRecordingProgress(progress);
return <span>Recording: {duration.toFixed(1)}s</span>;
}
useRecordingSession
WebAudioProvider only. Tells the playlist that a take is being recorded into a track, for as long as isRecording is true. The provider then keeps playback running past the end of the audio and marks the track in the arrangement as the one the take is recording onto (arrangement.setTrackRecording), which plays it muted for the take, so what it already holds does not play under a punch-in that replaces it. useMixer().trackStates and the track's Mute button show it muted, its built-in <TrackMuteButton /> is disabled and useTrack().isRecording is true for it. The take's mute is no undo step and does not change the track's own mute (arrangement.getMixer()), so a mute changed during the take stays after it. The take's mute is cleared when the take ends, the track changes or the component unmounts; the provider also clears it when it unmounts itself. An <Activity> hide of the component ends the session the same way. When the component also calls useIntegratedRecording, that hide ends the take too (it is added to its track), so isRecording is false at the reveal; with isRecording from elsewhere still true, the reveal mutes the track again.
function useRecordingSession(options: RecordingSessionOptions): void;
interface RecordingSessionOptions {
/** True while a take is being recorded. */
isRecording: boolean;
/** The track being recorded into, or null when there is none. */
trackId: string | null | undefined;
}
Call it in the component that calls useIntegratedRecording. <WaveformRecordingPreview> only draws the take: without this hook the track is not muted for the take and plays as it is.
import { useRecordingSession } from '@waveform-playlist/browser';
const { isRecording, recordingTrackId } = useIntegratedRecording(arrangement, selectedTrackId);
useRecordingSession({ isRecording, trackId: recordingTrackId });
The hook runs setRecordingActive (from useEditorControls()) in an effect, which is after the render that follows the start of the take. A handler that starts playback together with the recording should also call setRecordingActive(true, trackId) itself, before play(). play() does nothing before the playlist's first ready (useTimeline().isReady), so a take started during the first load records without playback.
Edges to know: if the take's track is removed during a take as an undo step, the end of the take still clears its take mute, so undoing that removal after the take brings the track back with its own mute; undone during the take, it comes back muted until the take ends. An app's own mute control (one that does not use <TrackMuteButton />) reads useTrack().isRecording or tracks the take's track id itself: during a take muted is true because of the take, so a toggle from it (setMuted(!muted)) sets the track's own mute to false, and the track comes out of the take unmuted.
Drag & Drop Hooks
useClipDragHandlers
Handles clip dragging (move) and boundary trimming on the provider's arrangement (useArrangement()): WebAudioProvider only; it throws outside one and under MediaElementProvider. A move is one arrangement.moveClip() on drop. A trim is previewed in the view while the handle is dragged (only the dragged clip's view follows; the tracks do not change) and is one arrangement.trimClip() on release, so each is one undo step. Escape clears the preview and changes nothing. From onDragStart of a clip to its onDragEnd (or the unmount of the component that holds the handlers) useEditorControls().undo() / redo() do nothing (#848); a setup that calls onDragStart must also call onDragEnd, or undo stays off until that component unmounts. A move or a trim released while no engine is attached (before the first build, during a rebuild) is kept, and the next engine plays it. A move or a trim commits the clip and track picked up at drag start (by their ids), also if the row moves or other clips change position during the drag. A move whose clip is no longer in that track at the drop is dropped with a console warning. A clip still loading cannot be dragged (its placeholder has no handles). Collision detection for moves is ClipCollisionModifier, passed to the modifiers prop of DragDropProvider. A pointer move is turned into samples at the provider's zoom level (useZoom().samplesPerPixel), which the hook reads itself.
function useClipDragHandlers(options?: UseClipDragHandlersOptions): {
onDragStart: (event: DragStartEvent) => void;
onDragMove: (event: DragMoveEvent) => void;
onDragEnd: (event: DragEndEvent) => void;
};
Options
interface UseClipDragHandlersOptions {
/** Optional snap function for boundary trims: snaps a sample position to the nearest grid line. */
snapSamplePosition?: (samplePosition: number) => number;
}
Example
import { useMemo } from 'react';
import { DragDropProvider } from '@dnd-kit/react';
import { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';
import {
ClipCollisionModifier,
ClipInteractionOptions,
WaveformEditor,
useArrangement,
useAudioSettings,
useClipDragHandlers,
useDragSensors,
useZoom,
} from '@waveform-playlist/browser';
function EditablePlaylist() {
// The arrangement's tracks: a move stops at a clip still loading, as moveClip does.
const arrangement = useArrangement();
const { samplesPerPixel } = useZoom();
const { sampleRate } = useAudioSettings();
const sensors = useDragSensors();
const { onDragStart, onDragMove, onDragEnd } = useClipDragHandlers();
// Memoized: an array built in the JSX is a new `modifiers` prop on every render.
const modifiers = useMemo(
() => [
RestrictToHorizontalAxis,
ClipCollisionModifier.configure({
tracks: () => arrangement.getTracks(),
samplesPerPixel,
sampleRate,
}),
],
[arrangement, samplesPerPixel, sampleRate]
);
return (
<DragDropProvider
sensors={sensors}
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
modifiers={modifiers}
>
<ClipInteractionOptions enabled>
<WaveformEditor />
</ClipInteractionOptions>
</DragDropProvider>
);
}
useDragSensors
Pre-configured drag sensors for clip editing.
function useDragSensors(options?: DragSensorOptions): PluginDescriptor[];
useAnnotationDragHandlers
Drag handlers for the edges of annotation boxes, for @dnd-kit/react's DragDropProvider. <WaveformAnnotationBoxes> calls this hook itself and has its own DragDropProvider: with the built-in boxes you do not call it, and a DragDropProvider of your own around the view receives no annotation drag. Call it for a row of boxes you draw yourself (see the Annotations guide).
function useAnnotationDragHandlers(options: {
store: AnnotationStore | undefined; // usePlaybackControls().annotationStore
samplesPerPixel: number;
sampleRate?: number; // default 48000; pass the provider's
duration: number;
linkEndpoints: boolean;
preview?: AnnotationPreviewHandle;
}): { onDragStart; onDragMove; onDragEnd };
Pass preview: annotationPreview (from usePlaybackControls()) to keep the drag out of the store until it ends: each move is published to the preview, which the built-in annotation boxes and list follow, and the store is written once, on release. The drag keeps the start and end of every annotation it has touched (the dragged one and the neighbours it moved, also one moved back to where it was), and works out each move over the store's current list with those bounds on top, so a neighbour moved elsewhere during the drag stops the edge, or is carried by it, from where it is now. The release writes the touched bounds, by id, onto the store's list as it is then: an annotation added during the drag stays, and so does any other edit made elsewhere, except to the start and end of an annotation the drag has touched: those are the drag's. During the drag the preview shows the store's current list with the drag's bounds on top, so a change made elsewhere is drawn at once. Without preview, every move writes all the touched bounds, which re-renders whatever reads the annotations for each one. Without a store the handlers do nothing.
The drag ends and writes nothing more, its preview cleared, when the dragged annotation is removed from the store (a "clear all" included), when the store option becomes another store, or when the component unmounts. Without preview the moves already written stay.
Pressing Escape cancels the drag and puts back every annotation it touched, carried neighbours included: with preview nothing was written; without it each touched annotation's bounds from the start of the drag are written back.
useAnnotationsWithPreview
function useAnnotationsWithPreview(
annotations: readonly AnnotationData[],
preview: AnnotationPreviewHandle
): readonly AnnotationData[];
For a custom annotation list or row of boxes: returns the previewed annotations while an edge is being dragged with a preview, and annotations otherwise. Call it in the component that draws the annotations, so that only it re-renders per pointer move.
Clip Editing Hooks
useClipSplitting
Split clips at the playhead position. Each split is one arrangement.splitClip() on the provider's arrangement (useArrangement()): an undo step, kept also while no engine is attached; the engine and the view follow the arrangement. WebAudioProvider only: it throws outside one and under MediaElementProvider.
function useClipSplitting(): UseClipSplittingResult;
The split point is snapped at the provider's zoom level (useZoom().samplesPerPixel), which the hook reads itself.
Returns
interface UseClipSplittingResult {
splitClipAtPlayhead: () => boolean;
splitClipAt: (trackId: string, clipId: string, splitTime: number) => boolean;
}
splitClipAt takes the ids of the track and of the clip and returns false, changing nothing, for an id that is not in the arrangement, for a clip still loading, and for a split point outside the clip or too close to one of its edges (with a console warning). Otherwise it returns true, also with no engine attached. splitClipAtPlayhead() splits the loaded clip under the playhead on the selected track.
Example
function SplitButton() {
const { splitClipAtPlayhead } = useClipSplitting();
return (
<button onClick={splitClipAtPlayhead}>
Split Clip (S)
</button>
);
}
Effects Hooks
Both effects hooks also host third-party WAM 2.0 plugins alongside the built-in Tone.js effects — see the WAM Plugins guide for native-context setup, bypass semantics, WamEffectGui, and plugin discovery.
useDynamicEffects
Manage master effects chain with real-time parameter updates. The hook does not re-render when the chain changes, and everything it returns keeps its identity for the life of the component (masterEffects follows fftSize; availableEffects is read from the registry each time the calling component renders). Read the chain with useActiveEffects.
The chains are state: they survive a StrictMode remount, Fast Refresh and a hidden <Activity> with their lists and live instances; the hooks run no cleanup on unmount. Add defaults on mount behind a ref guard (an unguarded mount effect adds twice under StrictMode in development). After a real unmount the instances are disposed when the chain is garbage-collected (FinalizationRegistry; best effort, not prompt, not guaranteed); call clearAllEffects() / clearTrackEffects(trackId) to dispose them at a known moment. A clear also drops an add still in flight: its promise rejects with "…aborted: the effects chain was cleared before …". An unmount does not abort an add. If a change cannot be wired (a node on another AudioContext), the previous chain is restored, the new instance is disposed, the list is not changed and the add rejects. A type re-registered while its prepare was running is added as the new definition. See Lifetime of a chain.
function useDynamicEffects(fftSize?: number): UseDynamicEffectsReturn; // default: 256
Returns
interface UseDynamicEffectsReturn {
/**
* The master chain, in order. Read it with `useActiveEffects(effects)` in
* the component that draws the rack: this hook does not re-render when the
* list changes, so a slider step re-renders that component only.
*/
effects: ValueSource<ActiveEffect[]>;
/**
* The effects that can be added: the built-ins, then (in native-context
* mode) every type registered with `registerEffect()`. Read when the calling
* component renders, so register custom effects before it does.
*/
availableEffects: EffectDefinition[];
/**
* Adds a built-in effect or a registered custom effect by id. A built-in is
* in the chain before this returns. A registered type is added once its
* `prepare` hook has run on the audio context, and requires native-context
* mode (`configureGlobalContext({ nativeAudioContext: true })`).
* Resolves with the new entry's instanceId; rejects for an unknown id.
*/
addEffect: (effectId: string) => Promise<string>;
/**
* Hosts a WAM plugin from a module URL and appends it to the master chain.
* Requires native-context mode — call configureGlobalContext({ nativeAudioContext: true })
* from @waveform-playlist/playout before any audio initialization.
* WAM entries render in offline WAV export (re-instantiated on the offline context).
* Resolves with the new entry's instanceId.
*/
addWamEffect: (url: string, initialState?: unknown) => Promise<string>;
/** Live plugin handle for a hosted WAM entry (for GUI mounting via WamEffectGui). */
getWamPlugin: (instanceId: string) => WamPluginInstance | undefined;
removeEffect: (instanceId: string) => void;
/** Set a parameter on the live effect. For a registered custom effect a
* value that is not a number is ignored. */
updateParameter: (instanceId: string, paramName: string, value: EffectParameterValue) => void;
toggleBypass: (instanceId: string) => void;
reorderEffects: (fromIndex: number, toIndex: number) => void;
/**
* Remove and dispose every effect. An add that is still waiting (a
* registered effect's `prepare`, a WAM plugin loading) is dropped too: its
* promise rejects and nothing is appended after the clear.
*/
clearAllEffects: () => void;
masterEffects: EffectsFunction;
/**
* Returns the effects function for offline rendering (the same function on
* every call). It rebuilds the chain as it is when the export runs:
* built-in effects are re-created on the offline context, WAM entries
* re-instantiated with the live instance's state, registered custom effects
* prepared and created there; with no active effect it passes the audio
* straight through. It is async and may reject — a WAV export never
* silently renders without an effect the live chain has.
*/
createOfflineEffectsFunction: () => OfflineEffectsFunction;
analyserRef: RefObject<Analyser | null>;
}
type EffectParameterValue = number | string | boolean;
interface ActiveEffect {
instanceId: string;
effectId: string;
/**
* 'tone' = built-in Tone.js effect; 'wam' = hosted WAM plugin;
* 'custom' = a type registered with `registerEffect()` from
* `@waveform-playlist/core`.
*/
kind: 'tone' | 'wam' | 'custom';
/** Module URL for wam entries. */
url?: string;
definition: EffectDefinition;
params: Record<string, EffectParameterValue>;
bypassed: boolean;
/**
* The effect's wet/dry parameter, when it has one. Bypass sets it to 0 and
* leaves the effect in the chain; an effect without one is bypassed by
* disconnecting it.
*/
wetParam?: string;
}
ValueSource is from @waveform-playlist/core (see Value sources).
useTrackDynamicEffects
Per-track effects management. Each track id has its own chain. The hook does not re-render when a chain changes. The chains have the same lifetime as the master chain (see above): they survive a remount, and clearTrackEffects(trackId) disposes one track's effects.
function useTrackDynamicEffects(): UseTrackDynamicEffectsReturn;
Returns
interface UseTrackDynamicEffectsReturn {
/**
* One track's chain, in order. The same source is returned for the same
* track id. Read it with `useActiveEffects(getTrackEffects(trackId))` in
* the component that draws that track's effects: this hook does not
* re-render when a chain changes.
*/
getTrackEffects: (trackId: string) => ValueSource<TrackActiveEffect[]>;
/**
* Adds a built-in effect or a registered custom effect to a track by id. A
* built-in is in the chain before this returns. A registered type is added
* once its `prepare` hook has run on the audio context, and requires
* native-context mode. Resolves with the new entry's instanceId; rejects
* for an unknown id.
*/
addEffectToTrack: (trackId: string, effectId: string) => Promise<string>;
/**
* Hosts a WAM plugin from a module URL and appends it to a track's chain.
* Requires native-context mode — call configureGlobalContext({ nativeAudioContext: true })
* from @waveform-playlist/playout before any audio initialization.
* WAM entries render in offline WAV export (re-instantiated on the offline context).
* Resolves with the new entry's instanceId.
*/
addWamEffectToTrack: (trackId: string, url: string, initialState?: unknown) => Promise<string>;
/** Live plugin handle for a hosted WAM entry (for GUI mounting via WamEffectGui). */
getTrackWamPlugin: (trackId: string, instanceId: string) => WamPluginInstance | undefined;
removeEffectFromTrack: (trackId: string, instanceId: string) => void;
updateTrackEffectParameter: (
trackId: string,
instanceId: string,
paramName: string,
value: EffectParameterValue
) => void;
toggleBypass: (trackId: string, instanceId: string) => void;
reorderTrackEffects: (trackId: string, fromIndex: number, toIndex: number) => void;
/** Remove and dispose every effect of one track. An add to that track that
* is still waiting is dropped too: its promise rejects. */
clearTrackEffects: (trackId: string) => void;
/**
* The effects function of a track. The same function is returned for the
* same track id. Pass this function itself to the provider:
* `<WebAudioProvider trackEffects={getTrackEffectsFunction}>`.
*/
getTrackEffectsFunction: (trackId: string) => TrackEffectsFunction;
/**
* Returns a track's effects function for offline rendering (the same
* function for the same track id). It rebuilds the chain as it is when the
* export runs; with no active effect it passes the audio straight through.
* It is async and may reject — a WAV export never silently renders without
* an effect the live chain has.
*/
createOfflineTrackEffectsFunction: (trackId: string) => OfflineTrackEffectsFunction;
/**
* The effects that can be added: the built-ins, then (in native-context
* mode) every type registered with `registerEffect()`. Read when the calling
* component renders, so register custom effects before it does.
*/
availableEffects: EffectDefinition[];
}
/** An entry of a track's chain. The same shape as a master-chain entry. */
type TrackActiveEffect = ActiveEffect;
useActiveEffects
Subscribe a component to one effects chain.
/**
* The effects of one chain, as React state: `effects` from
* `useDynamicEffects()`, or `getTrackEffects(trackId)` from
* `useTrackDynamicEffects()`. The calling component re-renders when that
* chain changes (an effect added, removed, moved, bypassed, or a parameter
* set), so call it in the component that draws the chain, not at the root of
* the page.
*/
function useActiveEffects(effects: ValueSource<ActiveEffect[]>): ActiveEffect[];
import { WebAudioProvider, Waveform, useArrangementTracks } from '@waveform-playlist/browser';
import type { Arrangement } from '@waveform-playlist/engine';
import {
useDynamicEffects,
useTrackDynamicEffects,
useActiveEffects,
type UseDynamicEffectsReturn,
type UseTrackDynamicEffectsReturn,
} from '@waveform-playlist/browser/tone';
function App({ arrangement }: { arrangement: Arrangement }) {
// Call each hook once and pass the result down. A second call creates a
// second, empty set of chains.
const masterFx = useDynamicEffects();
const trackFx = useTrackDynamicEffects();
const tracks = useArrangementTracks(arrangement);
return (
<WebAudioProvider
arrangement={arrangement}
effects={masterFx.masterEffects}
trackEffects={trackFx.getTrackEffectsFunction}
>
<MasterRack masterFx={masterFx} />
{tracks.map((track) => (
<TrackRack key={track.id} trackId={track.id} trackFx={trackFx} />
))}
<Waveform />
</WebAudioProvider>
);
}
function MasterRack({ masterFx }: { masterFx: UseDynamicEffectsReturn }) {
const activeEffects = useActiveEffects(masterFx.effects);
return (
<ul>
{activeEffects.map((effect) => (
<li key={effect.instanceId}>{effect.definition.name}</li>
))}
</ul>
);
}
function TrackRack({
trackId,
trackFx,
}: {
trackId: string;
trackFx: UseTrackDynamicEffectsReturn;
}) {
const trackEffects = useActiveEffects(trackFx.getTrackEffects(trackId));
return (
<ul>
{trackEffects.map((effect) => (
<li key={effect.instanceId}>{effect.definition.name}</li>
))}
</ul>
);
}
getAvailableEffects
/**
* The effects that can be added right now: the built-in effects, followed by
* every registered custom effect when the app is in native-context mode (a
* registered effect cannot be added without it). Returns the same array until
* that set changes, so it is safe to read during render. It is a read, not a
* subscription: a type registered later appears the next time this is called.
*/
function getAvailableEffects(): EffectDefinition[];
Both hooks return this list as availableEffects, read when the calling component renders. Register custom effects before the component that shows the picker renders. Adding by id (addEffect('my-id')) does not depend on the list. Effects that belong to another library's own catalogue in the shared registry are not listed: when @dawcore/components is loaded on the same page, its native-* effects stay out of the React list (they are marked builtIn), and can still be added by id.
Effect types
type ParameterType = 'number' | 'select' | 'boolean';
interface EffectParameter {
name: string;
label: string;
type: ParameterType;
min?: number;
max?: number;
step?: number;
default: number | string | boolean;
unit?: string;
options?: { value: string | number; label: string }[];
}
/** The categories the built-in effects use. */
type BuiltInEffectCategory =
| 'delay'
| 'reverb'
| 'modulation'
| 'distortion'
| 'filter'
| 'dynamics'
| 'spatial'
| 'wam';
/** The known names, or any other string. */
type EffectCategory = BuiltInEffectCategory | (string & {});
interface EffectDefinition {
id: string;
name: string;
/**
* The built-in effects use the listed categories and WAM plugins use
* `'wam'`; a registered custom effect may name any category of its own.
*/
category: EffectCategory;
description: string;
parameters: EffectParameter[];
}
interface EffectInstance {
/** Where the chain connects into the effect. */
input: ToneAudioNode | AudioNode;
/** Where the chain continues from. The same node as `input` for a Tone.js
* effect or a WAM plugin; a registered custom effect may have two. */
output: ToneAudioNode | AudioNode;
id: string;
instanceId: string;
dispose: () => void;
setParameter: (name: string, value: number | string | boolean) => void;
getParameter: (name: string) => number | string | boolean | undefined;
connect: (destination: InputNode) => void;
disconnect: () => void;
}
interface CustomEffectInstance extends EffectInstance {
kind: 'custom';
/** What the registered definition's `create` returned. */
native: NativeEffectInstance; // from @waveform-playlist/core
}
Custom effects
A type registered with registerEffect() from @waveform-playlist/core can be added by id with addEffect(id) / addEffectToTrack(trackId, id). It requires native-context mode. addEffect awaits the definition's prepare itself; with <daw-editor>, whose addEffect() is synchronous, call await editor.prepareEffect(type) first. See the Custom Effects guide.
// From @waveform-playlist/core
function registerEffect(type: string, definition: NativeEffectDefinition): void;
function unregisterEffect(type: string): boolean;
function getEffectDefinitions(): Map<string, NativeEffectDefinition>;
interface NativeEffectDefinition {
label: string;
category: string;
defaults: Record<string, number>;
params: Record<string, EffectParamDef>;
/** Name of the wet/dry param, when the effect has one. Bypass zeroes it;
* effects without one are bypassed by disconnection. */
wetParam?: string;
/** Async setup that must finish before `create` can run on a context
* (typically `audioContext.audioWorklet.addModule(url)`). Runs once per
* context, including the OfflineAudioContext of every export. Must be safe
* to run more than once on the same context. */
prepare?: (audioContext: BaseAudioContext) => Promise<void>;
create: (audioContext: BaseAudioContext, params: Record<string, number>) => NativeEffectInstance;
/**
* Set by a host library on the effects of its own catalogue (dawcore's
* `native-*`), never by an app. A host lists its own catalogue plus what
* the app registered: the React effect picker leaves these out. The effect
* can still be added by id anywhere.
*/
builtIn?: boolean;
}
interface EffectParamDef {
min: number;
max: number;
step?: number;
/** 's', 'ms', 'Hz', 'dB', '%' … */
unit?: string;
/** Display name for a parameter panel. Defaults to the parameter's key. */
label?: string;
}
/**
* A live, wired effect. `input`/`output` are the chain attachment points
* (the same node for single-node effects). `applyParams` updates AudioParams
* in place — the chain never rebuilds for parameter changes.
*
* The host owns every connection OUT of `output`: when it rewires the chain
* it disconnects all of them. Do not connect `output` to anything inside the
* effect (a feedback path, say); take such a tap from a node before it.
*/
interface NativeEffectInstance {
input: AudioNode;
output: AudioNode;
applyParams: (params: Record<string, number>) => void;
dispose?: () => void;
getState?: () => Promise<unknown>;
createGui?: () => Promise<HTMLElement>;
destroyGui?: (gui: HTMLElement) => void;
getParameterInfo?: () => Promise<unknown>;
}
Recording Hooks
From @waveform-playlist/recording:
useMicrophoneAccess
function useMicrophoneAccess(): {
stream: MediaStream | null; // the open microphone; null while none is open
devices: MicrophoneDevice[];
hasLabels: boolean; // devices names the real microphones (false before a first grant)
isLoading: boolean;
error: Error | null;
requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
stopStream: () => void;
};
useRecording
function useRecording(
stream: MediaStream | null,
options?: RecordingOptions
): {
isRecording: boolean;
isPaused: boolean;
/** Elapsed time and live-preview peaks: { duration, peaks }. A source, not
* state; published once per animation frame while recording. After a stop,
* duration is the recorded buffer's length. */
progress: RecordingProgressSource;
audioBuffer: AudioBuffer | null;
/** Resolves true when the capture pipeline actually started. */
startRecording: () => Promise<boolean>;
stopRecording: () => Promise<AudioBuffer | null>;
pauseRecording: () => void;
resumeRecording: () => void;
error: Error | null;
};
useRecordingProgress
A recording's elapsed time and preview peaks as React state, at most updateRate times a second. Use it for slow displays such as an elapsed-time label. The live waveform takes the source itself (<WaveformRecordingPreview recordingState={{ …, progress }} />).
function useRecordingProgress(
progress: RecordingProgressSource,
options?: { updateRate?: number } // Default: 10 (updates per second)
): RecordingProgress; // { duration: number; peaks: (Int8Array | Int16Array)[] }
useMicrophoneLevel
function useMicrophoneLevel(
stream: MediaStream | null,
options?: {
channelCount?: number; // Default: 1 (mono). Set to 2 for stereo.
updateRate?: number; // Default: 60 (Hz)
}
): {
meter: MeterSource; // Live { levels, peakLevels, rmsLevels } per channel (0-1); a source, not state
resetPeak: () => void; // Reset all held peak levels
error: Error | null; // Meter setup error
};
Value sources
Meter levels and recording progress change about 60 times a second. Held in React state, they would re-render the component that calls the hook at that rate. The hooks return a source instead, and the hook's component does not re-render when the value changes.
// From @waveform-playlist/core
interface ValueSource<T> {
subscribe(listener: (value: T) => void): () => void; // returns unsubscribe
getSnapshot(): T; // same object until the next change
}
interface MeterLevels {
levels: number[]; // Per-channel smoothed peak levels (0-1)
peakLevels: number[]; // Per-channel held peak levels since the last reset (0-1)
rmsLevels: number[]; // Per-channel RMS levels (0-1)
}
type MeterSource = ValueSource<MeterLevels>;
interface RecordingProgress {
duration: number; // Elapsed seconds
peaks: (Int8Array | Int16Array)[]; // Per-channel preview peaks
}
type RecordingProgressSource = ValueSource<RecordingProgress>;
Four ways to read one:
// 1. Hand it to the component that draws it.
<SegmentedVUMeter meter={meter} />
// 2. Throttled React state: at most `updateRate` renders a second (default 10).
const { levels, peakLevels, rmsLevels } = useMeterLevels(meter, { updateRate: 10 });
const { duration } = useRecordingProgress(progress);
const value = useThrottledValue(anySource); // generic form
// 3. Full-rate React state.
const { levels } = useSyncExternalStore(meter.subscribe, meter.getSnapshot);
// 4. Draw it yourself, without rendering.
useEffect(() => meter.subscribe(({ levels }) => drawBars(levels)), [meter]);
useMeterLevels and useThrottledValue come from @waveform-playlist/ui-components; useRecordingProgress from @waveform-playlist/recording.
useOutputMeter
From @waveform-playlist/browser/tone
Monitor the master output level of the playlist. Must be used inside WebAudioProvider.
function useOutputMeter(options?: UseOutputMeterOptions): UseOutputMeterReturn;
Options
interface UseOutputMeterOptions {
channelCount?: number; // Default: 2
updateRate?: number; // Default: 60 (Hz)
isPlaying?: boolean; // Reset levels when false (prevents frozen meters)
}
Returns
interface UseOutputMeterReturn {
meter: MeterSource; // Live { levels, peakLevels, rmsLevels } per channel (0-1); a source, not state
resetPeak: () => void; // Reset all peak hold indicators
error: Error | null; // Meter setup error
}
Example
import { useOutputMeter } from '@waveform-playlist/browser/tone';
import { useMeterLevels } from '@waveform-playlist/ui-components';
function OutputMeter() {
const { meter, resetPeak } = useOutputMeter({ channelCount: 2 });
// Text readout: 10 renders a second is enough.
const { levels, peakLevels } = useMeterLevels(meter);
return (
<div>
{levels.map((level, ch) => (
<div key={ch}>
<span>{ch === 0 ? 'L' : 'R'}: {(level * 100).toFixed(0)}%</span>
<span>Peak: {(peakLevels[ch] * 100).toFixed(0)}%</span>
</div>
))}
<button onClick={resetPeak}>Reset Peak</button>
</div>
);
}
Export Hooks
useExportWav
Export the playlist to WAV format using offline rendering.
function useExportWav(): {
exportWav: (
tracks: readonly ClipTrack[],
trackStates: readonly (TrackState | undefined)[],
options?: ExportOptions
) => Promise<ExportResult>;
isExporting: boolean; // true while any export started from this hook call is running
progress: number; // milestone 0, 0.1, 0.9 or 1 of the export started last from this hook call
error: string | null; // message of the last failed export; cleared when an export starts
};
trackStates[i] is the mix of tracks[i]; a track with no entry is rendered with its own muted, soloed, volume and pan, the values it was created with and not the arrangement's current mix (under the provider, useMixer().trackStates has an entry for every track). An export refused at once (no tracks, an unknown trackId) rejects and sets error without changing isExporting or progress. The state belongs to the hook call: each useExportWav() has its own, so ExportWavButton's is not visible to the page. To show it, call useExportWav() and draw the button yourself (the example below).
progress is a milestone, not a measured fraction of rendering. It resets to 0 on start. The onProgress callback reports 0.1 before offline rendering, 0.9 after it, and 1 after WAV encoding. It does not run during the offline render, so show an indeterminate state if you draw your own export button.
ExportOptions
interface ExportOptions {
filename?: string; // Filename for download (default: 'export'); one track: '<filename>_<track name>', control characters and / \ : * ? " < > | in the name replaced by _
trackId?: string; // The one track to export; left out or undefined, the mix
bitDepth?: 16 | 32; // WAV bit depth (default: 16)
effectsFunction?: OfflineEffectsFunction; // Master effects chain for export (native + WAM)
createOfflineTrackEffects?: (trackId: string) => OfflineTrackEffectsFunction | undefined; // Each track's chain
autoDownload?: boolean; // Trigger automatic download (default: true)
onProgress?: (progress: number) => void;
}
- The mix (no
trackId): every audible track. A muted track is left out, soloed or not; when a track is soloed, only soloed tracks are audible. Two channels when any audible track is stereo (a stereo clip or the stereo pan law), else one. - One track (
trackId): that track as it sounds on its own, with its volume, pan and track effects, through the master chain wheneffectsFunctionis given; its mute and the other tracks' solo are ignored. The file lasts as long as the mix (to the end of the last clip on any track, plus 0.1 s), so stems exported one by one line up (when each is exported after loading has finished:trackshold loaded clips only). Any value that is not the id of one oftracks(nullincluded; only a left-out orundefinedtrackIdmeans the mix) rejects withNo track with id "<id>" to export. - Fades are always rendered. Effects are rendered when their functions are given: leave out
effectsFunctionandcreateOfflineTrackEffectsfor an export without effects.
Effects Function
When an effectsFunction is provided, export renders through the effects chain — native Tone.js effects and hosted WAM plugins alike. WAM entries are re-instantiated on the offline context from their URL-cached factories with the live instance's state transferred; a WAM plugin that fails to re-instantiate fails the export. The function may return a cleanup callback synchronously or asynchronously.
type OfflineEffectsCleanup = void | (() => void);
type OfflineEffectsFunction = (
masterVolume: Volume,
destination: ToneAudioNode,
isOffline: boolean // true during export
) => OfflineEffectsCleanup | Promise<OfflineEffectsCleanup>;
ExportResult
interface ExportResult {
audioBuffer: AudioBuffer; // Rendered audio buffer
blob: Blob; // WAV file as Blob
duration: number; // Duration in seconds
}
Example
useTimeline().tracks holds loaded clips only, so an export started while audio is still loading renders the clips that have loaded.
function ExportButton() {
const { tracks } = useTimeline();
const { trackStates } = useMixer();
const { exportWav, isExporting } = useExportWav();
const handleExport = async () => {
try {
const result = await exportWav(tracks, trackStates, {
filename: 'my-mix',
bitDepth: 16,
});
console.log('Exported:', result.duration, 'seconds');
} catch (error) {
console.error('Export failed:', error);
}
};
return (
<button onClick={handleExport} disabled={isExporting}>
{isExporting ? 'Exporting WAV…' : 'Export WAV'}
</button>
);
}
Keyboard Shortcuts
usePlaybackShortcuts
Enable common playback keyboard shortcuts. WebAudioProvider only: the hook throws when the nearest playlist provider is MediaElementProvider.
Default Shortcuts
| Key | Action |
|---|---|
Space | Toggle play/pause |
Escape | Stop playback (during a drag it only cancels the drag, #848) |
0 | Rewind to start |
Each is the key alone: with Ctrl, Cmd or Alt held (Space also with Shift) the key is left to the browser and to your own shortcuts. The bindings are DEFAULT_PLAYBACK_SHORTCUTS in @waveform-playlist/core, the same keys <daw-keyboard-shortcuts playback> uses.
Signature
function usePlaybackShortcuts(options?: UsePlaybackShortcutsOptions): {
togglePlayPause: () => void;
stopPlayback: () => void;
rewindToStart: () => void;
shortcuts: KeyboardShortcut[];
};
Options
interface UsePlaybackShortcutsOptions {
enabled?: boolean; // Enable shortcuts (default: true)
additionalShortcuts?: KeyboardShortcut[]; // Your own shortcuts, matched before the defaults
playbackShortcuts?: PlaybackShortcutMap | null; // Another key per default action: { playPause: { key: 'p' } }
shortcuts?: KeyboardShortcut[]; // Override all shortcuts
}
Example
// Basic usage - enables default shortcuts
usePlaybackShortcuts();
// With additional custom shortcuts. They are matched first, so the one on
// Space runs in place of the default play/pause.
usePlaybackShortcuts({
additionalShortcuts: [
{ key: 's', action: splitClipAtPlayhead, description: 'Split clip' },
{ key: ' ', action: togglePlay, description: 'Play/Pause' },
],
});
// Override defaults completely
usePlaybackShortcuts({
shortcuts: [
{ key: 'Home', action: rewindToStart, description: 'Go to start' },
],
});
useKeyboardShortcuts
Low-level hook for custom keyboard shortcuts.
Signature
function useKeyboardShortcuts(options: UseKeyboardShortcutsOptions): void;
KeyboardShortcut
interface KeyboardShortcut {
key: string; // Key to listen for
action: () => void; // Function to call
ctrlKey?: boolean; // true: Ctrl must be held; unset or false: must not be
shiftKey?: boolean; // true: Shift must be held; false: must not be; unset: either
metaKey?: boolean; // true: Meta/Cmd must be held; unset or false: must not be
altKey?: boolean; // true: Alt must be held; unset or false: must not be
description?: string; // Human-readable description
preventDefault?: boolean; // Prevent default behavior (default: true)
}
A shortcut runs only on its exact Ctrl, Cmd (metaKey) and Alt state: one that names none of them is the key alone, so { key: 's' } does not run on Cmd+S. Shift is the exception: left unset it matches with or without Shift, because Shift changes the key itself (?, {); shiftKey: true and shiftKey: false are exact. For a shortcut on both Ctrl+K and Cmd+K, list two. Of two shortcuts in the list that match a key press, the first runs.
Example
useKeyboardShortcuts({
shortcuts: [
{
key: 's',
action: () => splitClip(),
description: 'Split clip at playhead',
},
{
key: 'z',
metaKey: true,
action: () => undo(),
description: 'Undo',
},
{
key: 'z',
metaKey: true,
shiftKey: true,
action: () => redo(),
description: 'Redo',
},
],
enabled: !isInputFocused,
});
A label for a shortcut
The library draws no text for a shortcut and exports no label function. Build the label from the shortcut's own fields (key, metaKey, ctrlKey, altKey, shiftKey), with your app's names for the keys and the modifiers:
import type { KeyboardShortcut } from '@waveform-playlist/core';
// Your own names for the keys that need one, in your own language.
const KEY_NAMES: Record<string, string> = { ' ': 'Space' };
const shortcutLabel = (shortcut: KeyboardShortcut): string =>
[
shortcut.metaKey ? 'Cmd' : null,
shortcut.ctrlKey ? 'Ctrl' : null,
shortcut.altKey ? 'Alt' : null,
shortcut.shiftKey ? 'Shift' : null,
KEY_NAMES[shortcut.key] ?? shortcut.key.toUpperCase(),
]
.filter(Boolean)
.join('+');
shortcutLabel({ key: 's', metaKey: true, shiftKey: true, action: save }); // "Cmd+Shift+S"
shortcutLabel({ key: ' ', action: togglePlay }); // "Space"
Best Practices
1. Use Specific Hooks
Use the split context hooks for optimal performance:
// Re-renders on play, pause and stop only
const { isPlaying } = useIsPlaying();
const { play, pause } = usePlaybackControls();
2. Memoize Callbacks
When passing to child components:
const handleVolumeChange = useCallback((value: number) => {
setVolume(value);
}, [setVolume]);
3. Context Boundaries
Hooks must be used within their providers:
// Correct
<WebAudioProvider>
<ComponentUsingHooks />
</WebAudioProvider>
// Error
<ComponentUsingHooks /> // Outside provider