Spectrogram Visualization
Waveform Playlist can render tracks as FFT spectrograms — color-mapped time-frequency plots derived from the audio. Two flavors:
- React — the
@waveform-playlist/spectrogrampackage provides<SpectrogramProvider>(plus optional menu / modal UI), which goes inside<WebAudioProvider>, around the view. - Web Components —
<daw-track render-mode="spectrogram">on<daw-editor>, backed by@dawcore/spectrogram.
Both paths share the same framework-agnostic computation and Web Worker pool. The dawcore elements also use SpectrogramOrchestrator (viewport-aware chunked rendering, generation-based abort, color LUT cache); the React Provider keeps its own chunked pipeline.
React
Installation
npm install @waveform-playlist/spectrogram@next
@dawcore/spectrogram (which carries the FFT, worker, and orchestrator) is a regular dependency and will be installed automatically.
Basic Usage
Put <SpectrogramProvider> inside <WebAudioProvider>, around the view, and set a track's renderMode:
import { WebAudioProvider, Waveform, useCreateArrangement } from '@waveform-playlist/browser';
import { audioTrack } from '@waveform-playlist/core';
import { SpectrogramProvider } from '@waveform-playlist/spectrogram';
function MyEditor() {
const arrangement = useCreateArrangement(() => [
audioTrack({ src: '/audio/vocals.opus', name: 'Vocals', renderMode: 'spectrogram' }),
]);
return (
<WebAudioProvider arrangement={arrangement}>
<SpectrogramProvider config={{ fftSize: 2048, frequencyScale: 'mel' }} colorMap="viridis">
<Waveform />
</SpectrogramProvider>
</WebAudioProvider>
);
}
The provider exposes one config + one color map at a time. Per-track settings come from the track's own spectrogramConfig / spectrogramColorMap fields.
The track menu, useTrack().setRenderMode and the settings dialog change the track's own renderMode, spectrogramConfig and spectrogramColorMap in the arrangement. Each change is an undo step, and arrangement.getTracks() holds it, so an app that saves its tracks saves the user's choices.
Render Modes
Each track has a renderMode field:
| Mode | Renders |
|---|---|
'waveform' (default) | Time-domain waveform |
'spectrogram' | FFT spectrogram only |
'both' | Waveform on top, spectrogram below |
Optional UI
Under a SpectrogramProvider the default track controls show a track menu on every audio track (not on MIDI tracks): radio buttons for the render mode (Waveform, Spectrogram, Both) and a "Spectrogram Settings..." entry that opens the settings dialog of that track. In a control panel you compose yourself, the menu is the piece <TrackMenuButton /> from @waveform-playlist/browser, and a component of your own reaches the same two things through useTrack():
import { useTrack } from '@waveform-playlist/browser';
// Among the children of <WaveformTrackControls>
function SpectrogramButtons() {
const { hasSpectrogram, renderMode, setRenderMode, openSpectrogramSettings } = useTrack();
// false for a MIDI track, and without a SpectrogramProvider
if (!hasSpectrogram) return null;
return (
<>
<button onClick={() => setRenderMode(renderMode === 'both' ? 'waveform' : 'both')}>
Spectrogram
</button>
<button onClick={openSpectrogramSettings}>Settings</button>
</>
);
}
See The Panel of a Track.
The package also exports the two pieces the provider builds that UI from, for a menu or dialog of your own:
spectrogramMenuItems(options)is a function, not a component (namedSpectrogramMenuItemsuntil #828): it takes{ renderMode, onRenderModeChange, onOpenSettings, onClose? }and returns an array ofTrackMenuItem(the render-mode radios and the settings entry) for theitemsofTrackMenu. BothTrackMenuand theTrackMenuItemtype are exports of@waveform-playlist/ui-components; the spectrogram package does not export the type. It has no colour-map items; the colour map is chosen in the settings dialog.<SpectrogramSettingsModal open onClose config colorMap onApply sampleRate />is the settings dialog (FFT size, frequency scale, gain, range and the rest). It reads no context: you pass the currentconfigandcolorMap, andonApplygets theconfigyou passed with the fields the user changed on top (the others,alphaand the label colours included, are kept as they were) and the colour map (yours, unless the user picked a named one). A field set back to what the dialog showed for it (the default, for a fieldconfigdoes not have) is not a change and is not written. When nothing was changed, Apply only closes the dialog andonApplyis not called. The optionalsampleRateis what the Max Frequency field shows half of whenconfighas nomaxFrequency: the top the spectrogram is drawn to by default. An emptied Min Frequency, Max Frequency, Gain or Range means unset: the field is left out of theconfigthatonApplygets, and the default draws. AhopSizeinconfigthat is none of the dialog's four overlap steps is shown as an option of its own ("300 (custom)") and kept until the user picks another or changes the FFT size.
Web Components
Installation
npm install @dawcore/components@next
@dawcore/spectrogram is a regular dependency — no extra install needed.
Declarative Usage
<daw-editor id="editor">
<daw-track src="/audio/vocals.opus" name="Vocals" render-mode="spectrogram"></daw-track>
</daw-editor>
<script type="module">
import '@dawcore/components';
import { NativePlayoutAdapter } from '@dawcore/transport';
const editor = document.getElementById('editor');
editor.adapter = new NativePlayoutAdapter(new AudioContext());
// Global defaults for every spectrogram track
editor.spectrogramConfig = { fftSize: 2048, frequencyScale: 'mel' };
editor.spectrogramColorMap = 'magma';
</script>
The spectrogram worker pool is created lazily on the first track that uses render-mode="spectrogram" (or "both") and torn down when no spectrogram tracks remain. No consumer-facing pool API.
Per-Track Overrides
Set spectrogramConfig on an individual <daw-track> to override the editor-wide defaults for that track only:
const track = editor.querySelector('daw-track');
track.spectrogramConfig = { colorMap: 'magma', minFrequency: 80, maxFrequency: 8000 };
Reset by assigning null:
track.spectrogramConfig = null; // falls back to editor defaults
Runtime Mode Switching
renderMode is a reflected attribute — flip it any time:
track.renderMode = 'both';
// or
track.setAttribute('render-mode', 'spectrogram');
daw-spectrogram-ready event
Fires (bubbling, composed) when the viewport-tier FFT completes for a track. Useful for E2E tests and screenshot tooling.
editor.addEventListener('daw-spectrogram-ready', (e) => {
console.log('Spectrogram ready for track:', e.detail.trackId);
});
SpectrogramConfig
Both paths accept the same config shape (from @waveform-playlist/core):
interface SpectrogramConfig {
fftSize?: 256 | 512 | 1024 | 2048 | 4096 | 8192; // Default: 2048
hopSize?: number; // Default: fftSize / 4
windowFunction?: 'hann' | 'hamming' | 'blackman' | 'rectangular' | 'bartlett' | 'blackman-harris'; // Default: 'hann'
alpha?: number; // Window-function parameter (0-1)
frequencyScale?: 'linear' | 'logarithmic' | 'mel' | 'bark' | 'erb'; // Default: 'mel'
minFrequency?: number; // Default: 0
maxFrequency?: number; // Default: sampleRate / 2
gainDb?: number; // Display brightness boost. Default: 20
rangeDb?: number; // Signal range. Default: 80
zeroPaddingFactor?: number; // FFT length multiplier. Default: 2
labels?: boolean; // Frequency axis labels
labelsColor?: string;
labelsBackground?: string;
}
colorMap is NOT inside SpectrogramConfig — it's a separate prop on <SpectrogramProvider> (React) or a separate property editor.spectrogramColorMap / track.spectrogramColorMap (Web Components). Mixing it into SpectrogramConfig will fail typecheck.
Color Maps
Six built-in maps available as string names:
type ColorMapName = 'viridis' | 'magma' | 'inferno' | 'grayscale' | 'igray' | 'roseus';
Custom Color Maps
Pass an array of [r, g, b] or [r, g, b, a] entries (values 0-255) for a custom palette:
const fire = [
[0, 0, 0], // black (silence)
[128, 0, 0], // dark red
[255, 64, 0], // orange
[255, 200, 0], // yellow
[255, 255, 255], // white (peak)
];
// React
<SpectrogramProvider colorMap={fire}>...</SpectrogramProvider>
// Web Components
editor.spectrogramColorMap = fire;
The orchestrator builds a lookup table from the array once and caches it; runtime cost is identical to a named preset.
Frequency Scales
Five scales available — 'mel' is the default and best-suited for most audio:
| Scale | Use case |
|---|---|
'linear' | Equal Hz spacing — best for inspecting harmonic structure |
'logarithmic' | Pitch-perceptual spacing (octaves get equal screen height) |
'mel' | Mel scale — perceptual scale for vocals and music |
'bark' | Bark scale — psychoacoustic, similar to mel |
'erb' | Equivalent Rectangular Bandwidth — cochlear-perception based |
The scale only affects rendering; the underlying FFT is the same. Switching scales reuses the cached FFT data — no recompute.
Pre-Computed Peaks Caveat
Spectrograms need the actual AudioBuffer (not pre-computed .dat peaks). If you load audio via peaks-src attribute (pre-computed peaks), the spectrogram won't render until the audio decode completes in the background. This is the same trade-off as recording's live preview.
Performance Notes
- Worker pool: one worker per audio channel (2 by default,
workerPoolSize), so the channels of a clip are computed in parallel. Only the audio of tracks that draw a spectrogram is sent to the workers. - Viewport-aware rendering — only visible chunks compute FFT; off-screen chunks defer until scrolled into view.
- Generation-based abort — zoom or config changes cancel in-flight FFT work for the old generation.
- Color LUT cache —
[r, g, b]lookup table built once per color map; reused across all tracks. - Chunked canvases — 1000px-wide canvas chunks (matches the waveform renderer) so large timelines stay responsive.