Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/engine-analysis
Copy to Clipboardimport { autoWarp, detectTransients, compressorOutput, bandGainForHandle, bandHandleDb, /* … */ } from "@/lib/engine/analysis";
| Export | Kind | What it is |
|---|---|---|
AutoWarp | interface | How a file plays in time at an arrangement's tempo, as autoWarp works it out. |
autoWarp | function | The warp that plays a recording of duration seconds in time at tempo BPM (CLP-019): a short one that a whole number of 1, 2, 4, 8 or 16 bars fits at its estimated tempo, as that loop, marked at its start and end; any other on a marker at the first beat of each bar, moved onto the transient within an eighth of a beat. |
detectTransients | function | Where channels have their transients, in seconds: each frame where the level rises sharply above what it does around it, found to the sample where the slope first reaches half its height there. |
TempoEstimate | interface | A recording's tempo, as @audio/beat-detect reads it and the registry's analyzeBeat fits it to the transients. |
CompressorSettings | interface | The transfer curve of a compressor: the output level in dB for each input level in dB, the textbook curve with a knee centred on the threshold, what a plug-in draws. |
compressorOutput | function | A compressor's transfer curve: the output level in dB for each input level in dB. |
BiquadSettings | interface | One filter as biquadResponse draws it: its type, frequency, gain and Q, at a sample rate. |
BiquadType | type | The kinds of band an equalizer draws: cuts, shelves, a peak, a notch and a band-pass. |
bandGainForHandle | function | The inverse, for dragging: the gain a band needs at frequency for its handle to sit at responseDb on the curve, so the handle follows the pointer one to one instead of the gain drifting from it. |
bandHandleDb | function | Where a band's handle sits on an equalizer's curve: the response of all the bands at the band's own frequency. |
biquadResponse | function | A biquad's gain in dB at hz, 0 being unity. |
EqBand | interface | One band of an equalizer: a filter that can be switched out of the chain. |
eqResponse | function | An equalizer's bands in series: their gains in dB add up at each frequency. |
SAMPLE_RATE | const | The sample rate a curve is drawn at unless a band says another. |
toWebAudioQ | function | The value to give a BiquadFilterNode's Q for a band's q. |
WEB_AUDIO_FILTER_TYPES | const | The Web Audio BiquadFilterNode type that does what each band type draws. |
dbToGain | function | The amplitude ratio of a level in dB: 0 dB is 1, -6.02 dB is 0.5. |
gainToDb | function | The level in dB of an amplitude ratio: 1 is 0 dB, 0.5 is -6.02 dB. |
peakDb | function | The level in dBFS of the loudest sample of samples, either way: how near the signal comes to clipping, where rmsDb says how loud it sounds. |
rmsDb | function | The RMS level of samples in dBFS: 0 dB for a square wave at full scale, -3 dB for a sine at full scale. |
createLoudnessMeter | function | Measures what is connected to it while it plays, on the audio thread, and calls onLoudness with its momentary, short-term and integrated loudness every 100 ms. |
createLoudnessReader | function | Reads loudness block by block: add takes the K-weighted mean square of the next 100 ms, summed over the channels, as the meter's processor posts it, and gives the loudness up to it. |
LiveLoudness | interface | How loud a sound is while it plays, in LUFS. |
LOUDNESS_TARGETS | const | Targets in LUFS: what streaming services, podcasts and broadcast (EBU R 128) ask a file to be. |
LOUDNESS_WORKLET | const | The meter's processor: it K-weights each channel of its input (a high shelf, then a high-pass, with the coefficients @audio/weighting-k gives for the context's rate), and posts the mean square of each block of 100 ms, summed over the channels. |
Loudness | interface | How loud a sound is. |
LoudnessMeter | interface | A live loudness meter on a context, as createLoudnessMeter makes it. |
loudnessGain | function | The gain in dB that brings a sound to target LUFS, as far as its true peak stays at or under ceiling dBTP: a sound that would pass it lands under the target instead, and nothing is limited. |
measureLoudness | function | Measures whole channels at once. |
AudioPeaks | interface | The lowest and highest sample of each slice of the audio, -1 to 1: what the Waveform draws as the waveform really is, lopsided where the audio is. |
computePeaks | function | Reduces PCM samples to bucketCount slices, keeping each slice's lowest and highest sample across every channel, a take panned hard to one side still draws, rather than reading as a flat line on the channel it isn't on. |
downsampleWaveform | function | Downsamples raw PCM samples into targetLength blocks, each block's value the peak (max) absolute amplitude within it, the reduction waveform visualizers use, since a block average flattens short transients into a softer-looking curve than the audio actually has. |
normalizePeaks | function | Scales peaks so the loudest sample, either way, reaches full height, keeping each slice's lopsidedness. |
normalizeWaveform | function | Scales values so the largest entry becomes 1, keeps a waveform's peak reaching full height regardless of the source audio's own loudness. |
SpectrumBandsOptions | interface | The frequencies and levels spectrumBands spreads its bands over. |
spectrumBands | function | Reduces an analyser's spectrum (getFloatFrequencyData: decibels per frequency bin) to bands.length levels of 0-1, low to high, written into bands. |
DetectPitchOptions | interface | What detectPitch looks for. |
detectPitch | function | The pitch the samples hold and how clear it is, or nothing: too quiet a signal, or no clear period. |
PitchEstimate | interface | What a detection found: the pitch and how periodic the sound is there. |
analyzeBeat | function | Reads a recording's beat, once, as it is decoded: what warpOnImport warps its clips by. |
audioChroma | function | How much of a recording's sound lies in each pitch class, C to B, summing to 1, read once as it is decoded: what a key is read from, with notes or without (detectKeys of the Scale menu). |
BeatAnalysis | interface | What a recording's beat is read as when it comes in: its tempo, if it has one, and its transients, in seconds. |
ACX | const | What ACX asks of an audiobook: the RMS between -23 and -18 dBFS, the peak at most -3 dBFS, the noise floor at most -60 dBFS RMS. |
AcxCheck | interface | One requirement and how the sound stands against it. |
AcxReport | interface | A sound against the ACX audiobook requirements. |
checkAcx | function | Checks a sound against ACX's requirements for an audiobook. |
reportSound | function | Reads a sound once, to tell what it is: its loudness, its key, its tempo, and whether it meets ACX's requirements. |
SoundReport | interface | What reportSound reads from a sound. |
detectSilences | function | Where channels pause between their sounds, as [from, to] in seconds, in order: each stretch of at least minDuration where every sample of every channel stays under the threshold, found to a block of 1024 frames. |
SilenceOptions | interface | What detectSilences takes, both optional. |
SPECTRA_SIZE | const | The frames of a window of the spectra, and of one of their columns: 2048, some 43 ms at 48 kHz, the window a spectrogram fits a view with. |
Spectra | interface | A recording summed up as spectra, for a spectrogram drawn on the GPU that does not hold the recording: a column every hop frames, each bin's level from DC to Nyquist over windows of size frames, a byte each. |
SpectraSource | interface | A reader of a recording, mixed to one: how many frames it holds, and its frames from from to to, at once or later. |
spectrogramSpectra | function | The spectra of a recording (Spectra): a column every hop frames, each bin's power over the Hann windows of size frames centred in the column every size / 2 frames (the short-time transform of @audio/stft), their mean, as a byte. |
holdPeaks | function | Keeps the loudest level each point of a spectrum reached: a peak rises with the spectrum at once, stays put for hold seconds, then falls at fall dB per second until the spectrum meets it again. |
LogSpectrumOptions | interface | The frequencies the axis of logSpectrum spans. |
logSpectrum | function | Fills out with bins (dB per analyser bin, as getFloatFrequencyData writes them) resampled onto a log axis. |
PeakHoldOptions | interface | How long holdPeaks holds a peak, and how fast it lets it fall. |
SPECTRUM_FLOOR_DB | const | The quietest a point is drawn: what a silent bin, -Infinity dB, becomes. |
stereoCorrelation | function | How alike the two channels of a sound are, from -1 to 1, as a correlation meter reads it: 1 when both carry the same sound (mono, at any levels), 0 when they have nothing in common or only one side sounds, and -1 when one is the other upside down, which cancels out once the two are summed to mono. |
BandShares | interface | What each slice of a sound is made of: the share of its lows, mids and highs, the loudest of the three being 1. |
Bands | interface | The three bands of a stretch of sound: its lows under 250 Hz, its highs over 2.5 kHz, and the mids between. |
bandShares | function | Reads a sound as count slices of equal length, each by how its energy is spread over three bands: the lows under 250 Hz, the highs over 2.5 kHz and the mids between. |
createBandSplit | function | Splits a sound in three a stretch at a time, as splitBands does: each call takes the stretch that follows the one before and carries the crossover's state over, so stretches split in order are the sound split whole. |
SplitBands | interface | A sound as three signals: what it has under 250 Hz, between, and over 2.5 kHz. |
splitBands | function | The sound's channels mixed to one and split in three by a Linkwitz-Riley crossover (@audio/eq-crossover, 24 dB an octave) at 250 Hz and 2.5 kHz: the three bands add back to the mix, level and phase. |
Usage
The functions take samples, bins or settings and return numbers, with no Web Audio node in them, so they run wherever the data is.
Levels
Copy to Clipboardimport { dbToGain, gainToDb, peakDb, rmsDb } from "@/lib/engine/analysis"; rmsDb(samples); // how loud they sound: -3 dB for a sine at full scale peakDb(samples); // how near they come to clipping: 0 dB for the same sine dbToGain(-6.02); // 0.5
The registry's useAudioLevels reads an analyser through them into what a Meter draws.
Spectrum
logSpectrum(bins, sampleRate, out, { minHz, maxHz }) resamples an analyser's bins (getFloatFrequencyData) onto a log frequency axis, written into out, as many points as it holds. holdPeaks(spectrum, peaks, holding, elapsed, { hold, fall }) keeps each point's loudest level for hold seconds, then lets it fall at fall dB a second, one frame at a time. spectrumBands reduces a spectrum to a few levels from 0 to 1, for bars. useSpectrum runs them on every frame.
spectrogramSpectra(source, { size, hop }) sums up a whole recording for a spectrogram drawn on the GPU that does not hold it: a column every hop frames, each bin's power over the Hann windows of size frames centred in it (the short-time transform of @audio/stft), as a byte, (dB + 150) · 1.6, 0 dB a full-scale sine on its bin. It reads source ({ frames, read }) a stretch at a time, at once or as a promise, so it runs on the page or in a worker over a file; made once and kept beside the recording, it is what a streamed recording's samples.spectra gives @/lib/webgl/spectrogram. SPECTRA_SIZE, 2048, is the default for both.
Copy to Clipboardimport { spectrogramSpectra } from "@/lib/engine/analysis"; const spectra = await spectrogramSpectra({ frames, read: readFrames });
Curves
A filter, an equalizer and a compressor each have a curve a panel draws. Each function returns the curve as a function, to be sampled at as many points as the plot has:
Copy to Clipboardimport { biquadResponse, compressorOutput, eqResponse } from "@/lib/engine/analysis"; const cut = biquadResponse({ type: "highcut", frequency: 1000 }); cut(1000); // -3.01 dB at the cutoff const eq = eqResponse([ { type: "peak", frequency: 1000, gainDb: 6, q: 1 }, { type: "highshelf", frequency: 8000, gainDb: -3 }, ]); eq(1000); // 6 dB: the bands add up at each frequency const compressor = compressorOutput({ thresholdDb: -20, ratio: 4 }); compressor(-8); // -17: 12 dB over the threshold comes out 3 dB over
The band types are the ones an equalizer shows (lowcut, highcut, lowshelf, highshelf, peak, notch, bandpass). WEB_AUDIO_FILTER_TYPES maps each to the BiquadFilterNode type that sounds as drawn, and toWebAudioQ converts a band's Q for the node. bandHandleDb and bandGainForHandle place a band's handle on the summed curve and back, so a dragged handle stays under the pointer.
Waveforms
computePeaks(channels, buckets) reduces a recording to the lowest and highest sample of each slice, across its channels, which is what a waveform draws; normalizePeaks scales them to full height.
Tempo and transients
detectTransients(channels, sampleRate) finds where a recording's level rises sharply, in seconds. detectSilences(channels, sampleRate) finds where it pauses between its sounds, as [from, to] in seconds: each stretch of at least 60 ms where every sample stays under -34 dBFS, or 20 dB under the loudest sample of a quiet recording (threshold in dBFS and minDuration in seconds set your own). Between them, an editor selects a sound as a text selects a word: from one transient to the next, or from one pause to the next. autoWarp works out how a recording plays in time at an arrangement's tempo, from a tempo estimate and those transients: a short recording that 1, 2, 4, 8 or 16 bars fit at its tempo is taken as that loop, marked at its start and end; any other gets a warp marker on the first beat of each bar, moved onto a transient within an eighth of a beat. It returns the tempo, the offset of the first beat and the markers, or null when there is no tempo to go by.
Loudness
loudness measures a whole sound the way streaming services and broadcasters do (ITU-R BS.1770): its integrated loudness in LUFS, its loudest sample, and its true peak, the loudest point of the waveform between the samples. loudnessGain is the gain that brings it to a target as far as its true peak stays under a ceiling, -1 dBTP unless told otherwise: a sound that would pass it lands under the target instead, and nothing is limited.
Copy to Clipboardimport { dbToGain } from "@/lib/engine/analysis"; import { LOUDNESS_TARGETS, loudnessGain, measureLoudness } from "@/lib/engine/analysis"; const loudness = measureLoudness(channels, sampleRate); // { lufs: -19.2, peak: -3.1, truePeak: -2.8 } const gain = dbToGain(loudnessGain(loudness, LOUDNESS_TARGETS.streaming)); const normalized = channels.map((channel) => channel.map((sample) => sample * gain));
It reads every sample, the true peak at four points a sample: about half a second a minute of loud stereo on a laptop, so measure where the page can wait, as an export does. LOUDNESS_TARGETS holds -14 LUFS for streaming, -16 for podcasts and -23 for broadcast (EBU R 128).
While it plays
useLoudness measures a node as it plays, on the audio thread: momentary, short-term and integrated LUFS every 100 ms as a live source, and clear to start the integrated loudness over.
Usage and API: useLoudness.
Pitch
detectPitch(samples, sampleRate, { minHz, maxHz, minLevel, threshold }) is the pitch a stretch of samples holds: the YIN algorithm of @audio/pitch-yin, between minHz and maxHz, which a stretch must hold two periods of the lowest of. It returns { frequency, confidence }, or null for a signal quieter than minLevel, an RMS level from 0 to 1, or with no clear period, such as noise or a chord. A tuner reads it a few dozen times a second and keeps the median of the last few readings; usePitch does that for a React page.
A recording as it comes in
Two readings are taken once, as a recording is decoded:
analyzeBeat(channels, sampleRate)reads its tempo with@audio/beat-detectand fits the beat grid on its transients, to the sample, so a tempo between whole BPM holds over a long file. It returns{ estimate, transients }, the estimatenullfor a sound with no attack (silence, noise), which is whatautoWarptakes.audioChroma(channels, sampleRate)is how much of its sound lies in each pitch class, C to B, summing to 1: the chroma of@audio/mir-chromaon each stretch that is not silence, averaged. It is what a key is read from, withdetectKeys.
Reading a sound
Copy to Clipboardimport { checkAcx, reportSound } from "@/lib/engine/analysis"; const report = reportSound(channels, sampleRate); report.loudness.lufs; // -19.5 report.key; // { name: "minor", root: 9 }, or null report.tempo; // 128, or null for a sound with no beat report.acx.pass; // RMS -23 to -18 dBFS, peak at most -3 dBFS, noise floor at most -60 dBFS checkAcx(channels, sampleRate).noiseFloor.value; // the quietest pause of half a second, in dBFS RMS, or null
reportSound reads every sample, a few seconds a minute of stereo on a laptop, so call it where the page can wait.
Colouring a waveform
Copy to Clipboardimport { splitBands } from "@/lib/engine/analysis"; const { low, mid, high } = splitBands(channels, sampleRate);
splitBands mixes the channels to one and splits them in three by a Linkwitz-Riley crossover (@audio/eq-crossover, 24 dB an octave) at 250 Hz and 2.5 kHz: the lows, the mids and the highs, which add back to the mix. Draw each as a waveform of its own, the lows warm and the highs cool, to colour a sound by its frequencies, as the registry's WaveformLane does with look="bands". It holds three copies of the mix, so call it when a view asks for it. A sound too long to hold is split a stretch at a time by createBandSplit(sampleRate), which carries the crossover's state from one stretch to the next, so stretches split in order are the sound split whole; a stretch split on its own settles after some tens of milliseconds, so read a few thousand frames before it. bandShares(channels, sampleRate, count) reads the same bands as shares per slice.