Skip to main content

Audio Spectrum Analyzer

What is a spectrum analyzer?​

An audio spectrum analyzer (British spelling: analyser) shows how loud a sound is at each frequency, updated live. Frequency runs along the horizontal axis, usually on a log scale from 20 Hz to 20 kHz, and level in decibels runs up the vertical axis. Peaks are tones and their harmonics; the low, ragged floor beneath them is noise.

A real-time audio spectrum analyser in a dark navy theme: the live FFT spectrum of an A major chord as a blue mountain on a logarithmic frequency axis from 20 Hz to 20 kHz, with sharp peaks at each note and its harmonics, an orange peak-hold line above, and level in decibels relative to digital full scale (dBFS) from -120 to 0

The live spectrum of an A major chord, with peak hold, sample data. Try the interactive analyser, with test signals or your own microphone.

Key takeaways
  • A spectrum analyser plots level against frequency; an oscilloscope plots level against time.
  • Software (FFT) analysers cut the sound into blocks, window each one, run an FFT, convert to decibels, then average and peak-hold the result.
  • A bigger FFT size separates closer frequencies but reacts more slowly.
  • Audio analysers use a log frequency axis because each octave matters equally to the ear; 1/3-octave bands group the FFT bins to match.
  • Pink noise slopes down 3 dB per octave in FFT bins but looks flat in 1/3-octave bands.

What does a spectrum analyzer measure?​

A spectrum analyser measures the level of a signal at each frequency. Any sound can be described as a sum of sine waves (the idea behind the Fourier transform); the analyser estimates how strong each of those sine waves is, and redraws the result many times a second.

From that one picture you can read:

  • tones and pitches: a whistle, a note or a hum shows as a narrow peak at its frequency;
  • harmonics: a musical note or a distorted tone shows a row of peaks at 2, 3, 4… times its fundamental frequency;
  • the noise floor: the level of the background hiss between the peaks, which sets the quietest thing you can see;
  • tonal balance: whether the energy sits mostly in the bass, the midrange or the treble;
  • bandwidth: how wide a range of frequencies a signal occupies.

It does not show when something happens within a block, or the phase of each component. For changes over time, use a spectrogram; for timing and waveform shape, use an oscilloscope.

How an FFT spectrum analyzer works​

Most software audio analysers, whether a plug-in, a phone app or a page in the browser, are FFT analysers (sound level meters and many 1/3-octave analysers use a bank of band filters to IEC 61260-1 instead). An FFT analyser repeats the same chain of steps for every new block of samples:

The signal chain of an FFT spectrum analyser, from left to right: capture at 48,000 samples per second, a block of N samples, a Hann window, the FFT, magnitude squared converted to decibels, averaging and peak hold, and the display on a log frequency axis. Below, the numbers for N = 4,096: each block lasts 85 ms, the bins are 11.7 Hz apart, and the result has 2,048 bins

  1. Capture a block. Take the latest NN samples, for example N=4,096N = 4{,}096 at a sample rate fsf_s of 48,000 samples per second: 85 ms of sound.
  2. Window it. Multiply the block by a window, such as Hann, that tapers both ends to zero. Without it, the abrupt edges of the block smear every tone across the spectrum (spectral leakage). The FFT guide shows why.
  3. Run the FFT. The fast Fourier transform turns the block into N/2N/2 frequency bins, spaced Δf=fs/N\Delta f = f_s / N apart (11.7 Hz here).
  4. Convert to decibels. Square each bin's magnitude to get power, scale it, and take 10log⁡1010 \log_{10}, so a sine of amplitude AA reads 20log⁡10A20 \log_{10} A (the formula is below).
  5. Average and hold. A single block of music or noise is jumpy. Averaging several blocks steadies the reading; peak hold keeps the highest level seen at each frequency.
  6. Display. Draw the levels against frequency, usually on a log axis, as a line, a filled "mountain" or bars.

The level of bin kk in step 4, in dBFS (decibels relative to digital full scale, where 0 dBFS is the largest sine the system can store), with X[k]X[k] the FFT output and w[n]w[n] the window, is:

Lk=10log⁡10 ⁣(4 ∣X[k]∣2(∑nw[n])2) dBFSL_k = 10 \log_{10}\!\left(\frac{4\,|X[k]|^2}{\left(\sum_n w[n]\right)^2}\right) \ \text{dBFS}

The factor of 4 and the window's sum undo the FFT's scaling and the window's loss, so a full-scale sine reads 0 dBFS whatever the FFT size or window.

A real-time analyser (RTA) is one that processes every sample, with no gaps between blocks, so a short click or burst can't slip through unseen. Analysers usually overlap the blocks (50% or 75%) too, so that the parts of the signal near the tapered ends of one block sit in the middle of the next. For audio, that's an easy load for a modern computer, even in plain JavaScript.

How to read an audio spectrum analyzer​

Read the level axis first, then the frequency axis, then the shape of the spectrum.

The level axis: dBFS, dBV, dBu and dB SPL​

The vertical axis is in decibels, a log scale where every 20 dB is a factor of ten in amplitude and 6 dB is roughly a factor of two. A decibel is always relative to a reference, and the unit name tells you which:

UnitReference (0 dB)Where you'll see it
dBFSDigital full scale: a full-scale sine wave, the loudest clean tone a digital system can storeSoftware analysers, DAWs, plug-ins. Values are almost always 0 or negative; a full-scale square wave reads +3 dBFS
dBV1 volt RMSMeasurement interfaces and analogue test gear
dBu0.775 volt RMSProfessional audio line levels (+4 dBu is a common nominal level)
dB SPL20 µPa of sound pressure, about the threshold of hearing at 1 kHzCalibrated measurement microphones, sound level meters, room acoustics

A software analyser that has not been calibrated against a known level can only show dBFS: it doesn't know your microphone's sensitivity or your interface's gain. Its readings are still useful for comparing frequencies with each other, which is most of what EQ and troubleshooting need.

The frequency axis: why a log scale​

Each octave (a doubling of frequency) sounds like the same size of step to the ear, whether it's 50 to 100 Hz or 5,000 to 10,000 Hz. On a logarithmic frequency axis, every octave gets the same width, so bass, midrange and treble each get a fair share of the screen. On a linear axis, the octave from 10 to 20 kHz takes up half of the chart and everything a voice or bass guitar does is squeezed into the left-hand edge. (The log scale guide covers log axes in general.)

Linear axes still have their uses: spotting evenly spaced harmonics, or reading vibration and electrical signals where the frequencies of interest are evenly spaced.

FFT bins vs octave and 1/3-octave bands​

An FFT gives bins of equal width in hertz. On a log axis that's very uneven: at N=4,096N = 4{,}096 and 48 kHz, the octave from 31.5 to 63 Hz contains only about three bins, while the octave from 8 to 16 kHz contains about 680. The bass is coarse and the treble is a dense comb.

Octave and 1/3-octave bands fix this by adding up the power of all the bins inside each band. Each band is a fixed fraction of an octave wide, so the bands are evenly spaced on a log axis. The 1/3-octave bands have standard centre frequencies: 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800 Hz, 1, 1.25, 1.6, 2, 2.5, 3.15, 4, 5, 6.3, 8, 10, 12.5, 16 and 20 kHz (the preferred frequencies of ISO 266; filter edges as in IEC 61260-1). There are 31 of them across the range of hearing, and each spans about 23% of its centre frequency. The demo below starts at 25 Hz, because at its default FFT size (4,096 samples at 48 kHz) no bin falls inside the 20 Hz band.

Two panels about FFT bins and 1/3-octave bands on a logarithmic frequency axis from 20 Hz to 20 kHz. Top: tick marks for FFT bins at a spacing of 11.7 Hz, sparse in the bass and so dense in the treble that they merge, with counts per octave from about 3 at 31.5 Hz to about 680 at 8 kHz. Bottom: the spectrum of pink noise, falling 3 dB per octave as an FFT line but level as 1/3-octave bars

So pink noise, which has equal power in every octave, looks different in the two views:

  • in FFT bins, it falls by 3 dB per octave (10 dB per decade), because each bin is the same width but the power per hertz halves with every octave;
  • in 1/3-octave bands, it is flat, because each band is twice as wide as the band an octave below it and catches twice as much power.

White noise does the opposite: flat in FFT bins, rising 3 dB per octave in bands. Bands match how we hear and are the norm for room tuning and noise measurement. FFT bins resolve individual tones, such as a 50 Hz hum and its harmonics. The power spectral density guide explains how noise levels depend on bandwidth.

At small FFT sizes, some of the lowest bands are narrower than the bin spacing and contain no bin at all, so they stay empty: the analyser has no information there. Bands holding just one or two bins are only rough estimates.

Spectrum analyzer settings: resolution, averaging and peak hold​

The FFT size, the averaging and peak hold decide how much detail you see and how quickly the display reacts.

SettingWhat it doesTrade-off
FFT size (NN)Sets the bin spacing, fs/Nf_s / N, and the block length, N/fsN / f_sBigger NN: finer frequency detail and a lower noise floor per bin, but a slower, smeared response to change. At 48 kHz: 1,024 gives 46.9 Hz bins every 21 ms; 16,384 gives 2.9 Hz bins every 341 ms
WindowTapers the block to reduce leakageHann suits most audio. Flat-top reads tone levels accurately but widens peaks; rectangular gives the sharpest peaks but the worst leakage
OverlapHow much each block shares with the previous oneMore overlap: smoother updates and no lost events, at more computation
AveragingCombines several spectra: exponential (each new spectrum nudges a running average) or linear (the mean of the last MM)More averaging: a steadier noise floor and clearer tones, but it hides short events and responds slowly
Peak holdKeeps the highest level reached at each frequencyCatches brief peaks such as feedback or a transient; must be reset to see the current state
WeightingApplies a frequency-dependent correction such as A-weightingMatches hearing at moderate levels; hides low-frequency rumble you might need to see

With exponential averaging, a smoothing factor α\alpha applied at rr updates per second makes the average forget old spectra with a time constant of about −1/(rln⁡α)-1/(r \ln \alpha). At 30 updates a second, α=0.8\alpha = 0.8 is about 0.15 s and α=0.95\alpha = 0.95 is about 0.65 s. The same α\alpha gives a different time constant if the display updates at a different rate.

Resolution bandwidth (RBW)​

Resolution bandwidth (RBW) is the width of the filter that each point on the display measures through. In a swept analyser, it is the width of the one filter that sweeps across the range. In an FFT analyser, the equivalent is the bin width times the window's equivalent noise bandwidth: about 1.5 bins for Hann and 1 for rectangular (Harris, 1978). At N=4,096N = 4{,}096 and 48 kHz with Hann, that's 1.5×11.7≈17.61.5 \times 11.7 \approx 17.6 Hz. Two tones closer than about two or three bins merge into one peak.

Noise floor and FFT size​

The displayed noise floor depends on the RBW as well as the noise. For broadband noise, each doubling of the FFT size lowers the floor by 3 dB, while a steady tone keeps its level. So a bigger FFT lets you see weaker tones buried in noise, at the cost of a slower response. Averaging doesn't lower the floor's average level; it makes it smoother, so small tones stand out of it. How far a signal sits above the floor is its signal-to-noise ratio.

A-weighting​

A-weighting is a standard correction curve (IEC 61672-1) that approximates the ear's lower sensitivity to bass and extreme treble at moderate levels. It is 0 dB at 1 kHz, about −16 dB at 125 Hz and −39 dB at 31.5 Hz, and within about 1.3 dB of 0 dB from 1 to 6 kHz, peaking at about +1.3 dB near 2.5 kHz. Sound levels quoted in dB(A) use it. It is the right choice for judging how loud noise sounds and for regulations, but the wrong one for finding a 50 Hz hum or a rumbling fan, which it hides: switch weighting off (Z-weighting) for troubleshooting.

Swept-tuned vs FFT spectrum analyzers​

The first spectrum analysers were swept-tuned. A single narrow filter, one resolution bandwidth (RBW) wide, is swept across the frequency range, and the display traces the level that comes through it. Radio-frequency analysers still use this design, often with a superheterodyne front end, which mixes the input with a tunable oscillator so that each frequency in turn is shifted down to one fixed intermediate frequency, where the filter does the measuring.

Swept-tuned analyserFFT analyser
How it measuresOne narrow filter sweeps across the span, a frequency at a timeCaptures a block of samples and computes every frequency at once
SpeedSlow sweeps for narrow RBWs; misses events at frequencies it isn't tuned to at that momentEvery frequency in each block; real-time with no gaps if processing keeps up
Frequency rangeHertz up to tens of gigahertzLimited by the converter's sample rate (half of it, the Nyquist frequency)
Typical useRadio, microwave and telecomsAudio, acoustics, vibration, and the digital back end of modern RF analysers

For sound, the range of interest is only 20 Hz to 20 kHz, and a sound card or audio interface samples fast enough to capture all of it (why 44.1 and 48 kHz), so audio analysers are FFT analysers.

What is a spectrum analyzer used for?​

A spectrum analyzer is used to see which frequencies are in a sound, and how loud each one is, while it plays.

  • Mixing and EQ: spotting where instruments overlap and pile up energy (often in the low mids), finding a harsh resonance to cut, and comparing a mix's tonal balance with a reference track.
  • Room acoustics: playing pink noise through the speakers and reading a 1/3-octave RTA at the listening position reveals room modes: the bass peaks and dips caused by the room's dimensions.
  • Hum and buzz: mains hum shows as a peak at 50 Hz (60 Hz in North America) with harmonics at 100, 150, 200 Hz…. A soft hum has few harmonics; a harsh buzz has many. A notch filter can remove it.
  • Feedback: in live sound, a feedback squeal is a single peak that grows; peak hold catches the frequency so it can be cut with a narrow EQ.
  • Loudspeakers and headphones: a sine sweep or noise signal shows the frequency response, its peaks and dips, and where the output falls away at each end (a Bode plot shows the same response with phase).
  • Machine noise and vibration: a rotating part makes peaks at its running speed and its multiples; a growing peak can be an early sign of wear in a bearing or gear.
  • Electronics and radio: checking amplifier distortion (harmonics of a pure tone), measuring a circuit's noise floor, and checking that a transmitter stays inside its channel.

Spectrum analyzer vs oscilloscope​

An oscilloscope and a spectrum analyser look at the same signal from two sides: the time domain and the frequency domain.

OscilloscopeSpectrum analyser
Horizontal axisTimeFrequency
Vertical axisVoltage (linear)Level, usually in dB (log)
Shows bestWaveform shape, timing, rise time, glitches, clippingTones, harmonics, noise floor, bandwidth, interference
Dynamic rangeSmall signals are hard to see next to large ones on a linear scaleA dB scale shows signals thousands of times weaker side by side
Typical questions"When does it happen? What shape is it?""Which frequencies are in it, and how strong is each?"
OverlapMany have an FFT or "math" mode"Zero span" mode shows level against time at one fixed frequency

The spectrogram: a spectrum analyzer with history​

An analyser shows only the latest spectrum. A spectrogram (or waterfall) keeps the history: time on one axis, frequency on the other, and level as colour. It shows how a sweep climbs, how a note's harmonics decay, or when a hum starts. Many audio tools show a waveform, a spectrum and a spectrogram together. See the spectrogram guide for how to read and build one.

Common spectrum analyzer mistakes​

Most mistakes in reading an analyser come from forgetting what the settings do to the display.

  • Reading the noise floor as the noise level. The floor in FFT bins depends on the FFT size and window; double NN and it drops 3 dB. Compare noise across settings with a PSD or fixed bands.
  • Using a linear frequency axis for audio. Everything below 1 kHz ends up crammed into a few pixels. Use a log axis.
  • Too small an FFT for bass. At 1,024 points and 48 kHz, the bins are 47 Hz apart, wider than the whole octave from 40 to 80 Hz. Use 8,192 or more to resolve low notes.
  • Too much averaging for live work. Heavy averaging hides feedback and transients. Use a short average with peak hold, or a spectrogram.
  • Leaving voice processing on. Browsers and phones apply echo cancellation, noise suppression and automatic gain to microphones by default; they reshape the spectrum. Turn them off for measurement.
  • Trusting uncalibrated levels. dBFS from a laptop microphone is not dB SPL. Calibrate with a known source before quoting absolute levels.
  • Forgetting weighting. An A-weighted display hides low-frequency problems; a Z-weighted (unweighted) one exaggerates rumble compared with how loud it sounds.

How to build an audio spectrum analyzer in JavaScript, React or Angular​

The analyser below runs a Hann-windowed FFT of up to 16,384 samples in your browser, up to 30 times a second, and redraws the spectrum as up to 8,191 bins or 30 bands: choose a test Signal, change the FFT size, Averaging, Peak hold, Display (FFT bins or 1/3-octave bands) and Frequency axis, and watch the spectrum react. The line under the controls gives the bin width and block length. Click Use my microphone to analyse your own sound; the browser asks for permission first, and nothing is recorded or sent anywhere. Hover to read a level, scroll to zoom, drag to pan and double-click to reset.

Things to try: switch Frequency axis between Log and Linear and watch the bass squeeze into the left-hand edge. Choose Pink noise and switch Display between FFT bins and 1/3-octave bands: the downward slope levels out in bands. Pick Two close tones (1,000 and 1,020 Hz), which zooms in around 1 kHz: at FFT sizes up to 4,096 you see one peak, and from 8,192 you see two. Choose 50 Hz hum to see the row of harmonics.

Here is the code. The JavaScript tab is the demo itself: test signals, a Hann window, a plain JavaScript FFT, averaging, peak hold and 1/3-octave bands, animated with requestAnimationFrame. The React and Angular tabs show the shortest route, the browser's built-in AnalyserNode, on live microphone input:

// Real-time audio spectrum analyser in JavaScript with SciChart.js: test signals or your microphone,
// windowed FFT, averaging, peak hold, FFT bins or 1/3-octave bands, on a log or linear frequency axis.
// The signal and FFT functions below are plain JavaScript with no dependencies, so you can use them anywhere.

// Iterative radix-2 Cooley-Tukey FFT, in place. re and im hold the real and imaginary parts;
// their length must be a power of 2. Afterwards, re[k] and im[k] hold frequency bin k.
function fft(re, im) {
const n = re.length;
if ((n & (n - 1)) !== 0) throw new Error("FFT length must be a power of 2");
// 1. Reorder the samples by bit-reversed index
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) {
[re[i], re[j]] = [re[j], re[i]];
[im[i], im[j]] = [im[j], im[i]];
}
}
// 2. Combine pairs of smaller DFTs into bigger ones with butterflies: a + w*b and a - w*b
for (let size = 2; size <= n; size *= 2) {
const half = size / 2;
const step = (-2 * Math.PI) / size;
for (let start = 0; start < n; start += size) {
for (let k = 0; k < half; k++) {
const wr = Math.cos(step * k);
const wi = Math.sin(step * k);
const a = start + k;
const b = a + half;
const tr = re[b] * wr - im[b] * wi;
const ti = re[b] * wi + im[b] * wr;
re[b] = re[a] - tr;
im[b] = im[a] - ti;
re[a] += tr;
im[a] += ti;
}
}
}
}

// Seeded random numbers, so the noise is the same every time the page loads.
// Box-Muller turns two uniform numbers into one Gaussian (normal) number with mean 0 and standard deviation 1.
function makeRandom(seed) {
let state = seed;
const uniform = () => {
state = (state * 16807) % 2147483647;
return (state - 0.5) / 2147483647; // strictly between 0 and 1
};
return () => Math.sqrt(-2 * Math.log(uniform())) * Math.cos(2 * Math.PI * uniform());
}

// A loop of pink noise (equal power in every octave): shape white noise in the frequency domain by scaling
// each bin's amplitude by 1/sqrt(f), then transform back. The loop repeats seamlessly. count is a power of 2.
function makePinkNoiseLoop(count, rms, seed) {
const gaussian = makeRandom(seed);
const re = new Float64Array(count);
const im = new Float64Array(count);
for (let i = 0; i < count; i++) re[i] = gaussian();
fft(re, im);
re[0] = 0; // no DC
im[0] = 0;
for (let k = 1; k < count; k++) {
const scale = 1 / Math.sqrt(Math.min(k, count - k)); // the same for bin k and its mirror, count - k
re[k] *= scale;
im[k] *= scale;
}
for (let k = 0; k < count; k++) im[k] = -im[k]; // inverse FFT: conjugate, transform, take the real part
fft(re, im);
let sumSquares = 0;
for (let i = 0; i < count; i++) sumSquares += re[i] * re[i];
const scale = rms / Math.sqrt(sumSquares / count);
return Float32Array.from(re, (v) => v * scale);
}

// Test signals, in digital full scale: 1.0 is the largest sample value, so a sine of amplitude 1 reads 0 dBFS.
// next() returns one sample at a time and keeps each oscillator's phase, so the sound runs on without clicks.
let pinkLoop = null; // made once, on first use
function createTestSignal(kind, sampleRate) {
pinkLoop = pinkLoop ?? makePinkNoiseLoop(131072, 1, 7);
const pink = pinkLoop;
let pinkIndex = 0;
const pinkSample = () => pink[pinkIndex++ & 131071];
const TWO_PI = 2 * Math.PI;
const tones = []; // [frequency in Hz, amplitude]
let noiseLevel = 0.0003; // a little background noise, about -70 dBFS
if (kind === "chord") {
// A major chord (A3, C#4, E4), each note with eight harmonics that get quieter, like a soft organ
for (const note of [220, 277.18, 329.63]) {
for (let h = 1; h <= 8; h++) tones.push([note * h, 0.15 / h]);
}
} else if (kind === "hum") {
// 50 Hz mains hum and a series of its harmonics, under a 1 kHz test tone
const harmonics = [0.25, 0.04, 0.1, 0.02, 0.06, 0.01, 0.035, 0.008, 0.02, 0.005, 0.012, 0.004, 0.008];
harmonics.forEach((amplitude, i) => tones.push([50 * (i + 1), amplitude]));
tones.push([1000, 0.1]);
} else if (kind === "close") {
// Two tones 20 Hz apart: an FFT of 4,096 points or fewer shows one peak, 8,192 or more shows two
tones.push([1000, 0.3], [1020, 0.3]);
} else if (kind === "pink") {
noiseLevel = 0.1; // pink noise at 0.1 RMS (-17 dB below a full-scale sine)
}
const phases = tones.map(() => 0);
// A logarithmic sine sweep from 20 Hz to 20 kHz every 6 seconds: each octave takes the same time
const SWEEP_SECONDS = 6;
let sweepTime = 0;
let sweepPhase = 0;
return function next() {
let value = noiseLevel * pinkSample();
if (kind === "sweep") {
const frequency = 20 * Math.pow(1000, sweepTime / SWEEP_SECONDS);
sweepPhase = (sweepPhase + (TWO_PI * frequency) / sampleRate) % TWO_PI;
sweepTime = (sweepTime + 1 / sampleRate) % SWEEP_SECONDS;
value += 0.5 * Math.sin(sweepPhase);
}
for (let t = 0; t < tones.length; t++) {
phases[t] = (phases[t] + (TWO_PI * tones[t][0]) / sampleRate) % TWO_PI;
value += tones[t][1] * Math.sin(phases[t]);
}
return value;
};
}

// 1/3-octave bands with base-10 centres, 1000 * 10^(n/10) Hz, from 25 Hz to 20 kHz.
// Each band runs from centre / 10^(1/20) to centre * 10^(1/20). Labels use the usual rounded (preferred) names.
const BAND_NAMES = ["25", "31.5", "40", "50", "63", "80", "100", "125", "160", "200", "250", "315", "400", "500", "630",
"800", "1k", "1.25k", "1.6k", "2k", "2.5k", "3.15k", "4k", "5k", "6.3k", "8k", "10k", "12.5k", "16k", "20k"];
const BANDS = BAND_NAMES.map((name, i) => {
const centre = 1000 * Math.pow(10, (i - 16) / 10);
return { name, centre, low: centre / Math.pow(10, 1 / 20), high: centre * Math.pow(10, 1 / 20) };
});

// The analyser: Hann window, FFT, power per bin, exponential averaging and peak hold.
// Levels are in dBFS, scaled so a full-scale sine reads 0 dBFS in its FFT bin and in its 1/3-octave band.
function createAnalyser(size) {
const window = new Float64Array(size);
let windowSum = 0;
let windowSumSquares = 0;
for (let i = 0; i < size; i++) {
window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / size); // periodic Hann
windowSum += window[i];
windowSumSquares += window[i] * window[i];
}
const re = new Float64Array(size);
const im = new Float64Array(size);
const bins = size / 2; // bins 1 to size/2 - 1 are drawn; bin 0 is DC, which a log axis can't show
const power = new Float64Array(bins); // averaged |X[k]|^2
let first = true;
const floorDb = -200;
const toDb = (p) => 10 * Math.log10(Math.max(p, 1e-20));

return {
size,
// samples: the newest `size` samples. smoothing: 0 (none) to 0.99 (heavy), like AnalyserNode.smoothingTimeConstant
analyse(samples, smoothing) {
for (let i = 0; i < size; i++) {
re[i] = samples[i] * window[i];
im[i] = 0;
}
fft(re, im);
const keep = first ? 0 : smoothing; // exponential average of power: new = keep * old + (1 - keep) * latest
for (let k = 1; k < bins; k++) {
power[k] = keep * power[k] + (1 - keep) * (re[k] * re[k] + im[k] * im[k]);
}
first = false;
},
// Level of each FFT bin: a sine's amplitude A shows as 20 log10(A) dBFS
binLevels(out) {
const scale = 4 / (windowSum * windowSum);
for (let k = 1; k < bins; k++) out[k - 1] = Math.max(toDb(power[k] * scale), floorDb);
},
// Level of each 1/3-octave band: the power of every bin inside it, added up (NaN if no bin falls inside)
bandLevels(sampleRate, out) {
const binWidth = sampleRate / size;
const scale = 4 / (size * windowSumSquares); // mean square of the band, relative to a full-scale sine (0.5)
BANDS.forEach((band, b) => {
const first = Math.max(1, Math.ceil(band.low / binWidth));
const last = Math.min(bins - 1, Math.ceil(band.high / binWidth) - 1);
let sum = 0;
for (let k = first; k <= last; k++) sum += power[k];
out[b] = last >= first ? Math.max(toDb(sum * scale), floorDb) : NaN;
});
}
};
}

// Optional microphone input. Asks for permission only when called, which must be from a click.
// Returns { sampleRate, read(buffer), stop() }; read() fills buffer with the newest samples (-1 to 1).
async function openMicrophone(size) {
if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia) {
throw new Error("the browser only allows the microphone on pages served over HTTPS");
}
// Turn off the voice-call processing, which would change the spectrum
const stream = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }
});
const audioContext = new AudioContext();
await audioContext.resume();
const analyserNode = audioContext.createAnalyser();
analyserNode.fftSize = size; // here only a buffer of the newest samples: the FFT is ours
audioContext.createMediaStreamSource(stream).connect(analyserNode);
return {
sampleRate: audioContext.sampleRate,
read: (buffer) => analyserNode.getFloatTimeDomainData(buffer),
stop: () => {
stream.getTracks().forEach((track) => track.stop());
audioContext.close();
}
};
}

async function createSpectrumAnalyser(chartDiv) {
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
ENumericFormat,
EAutoRange,
FastMountainRenderableSeries,
FastLineRenderableSeries,
FastRectangleRenderableSeries,
XyDataSeries,
XyxyDataSeries,
EColumnMode,
EColumnYMode,
GradientParams,
Point,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
ELegendPlacement,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

const MAX_SIZE = 16384;
const FLOOR_DB = -120; // bottom of the level axis
const { wasmContext, sciChartSurface } = await SciChartSurface.create(chartDiv, { theme: new SciChartJsNavyTheme() });

// Frequency axis: logarithmic (each octave the same width, as the ear hears it) or linear (each FFT bin the same width)
const makeFrequencyAxis = (isLog) => {
const options = {
axisTitle: isLog ? "Frequency (Hz, log scale)" : "Frequency (Hz)",
labelFormat: ENumericFormat.Engineering, // 100, 1K, 10K
labelPrecision: 0,
visibleRange: isLog ? new NumberRange(20, 20000) : new NumberRange(0, 20000),
majorGridLineStyle: { color: "#50C7E055" },
minorGridLineStyle: { color: "#50C7E01F" }
};
return isLog
? new LogarithmicAxis(wasmContext, { ...options, logBase: 10, autoTicks: false, majorDelta: 1, minorDelta: 1 })
: new NumericAxis(wasmContext, options);
};
sciChartSurface.xAxes.add(makeFrequencyAxis(true));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Level (dBFS)",
autoRange: EAutoRange.Never, // a fixed dB range stops the axis jumping with every frame
visibleRange: new NumberRange(FLOOR_DB, 5),
labelPrecision: 0
})
);

// FFT view: the live spectrum as a mountain, and a peak-hold line on top
const liveSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Live spectrum", dataIsSortedInX: true });
const peakSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Peak hold", dataIsSortedInX: true });
const liveMountain = new FastMountainRenderableSeries(wasmContext, {
dataSeries: liveSeries,
stroke: "#50C7E0",
strokeThickness: 2,
zeroLineY: FLOOR_DB - 100, // fill down past the bottom of the axis
fillLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
{ color: "#50C7E0AA", offset: 0 },
{ color: "#50C7E011", offset: 1 }
])
});
const peakLine = new FastLineRenderableSeries(wasmContext, { dataSeries: peakSeries, stroke: "#F48420", strokeThickness: 2 });

// 1/3-octave view: one bar per band (x = band edges, y = floor to level), and a thin peak-hold cap above each bar
const bandSeries = new XyxyDataSeries(wasmContext, { dataSeriesName: "1/3-octave bands" });
const bandPeakSeries = new XyxyDataSeries(wasmContext, { dataSeriesName: "Peak hold" });
const barOptions = { columnXMode: EColumnMode.StartEnd, columnYMode: EColumnYMode.TopBottom };
const bandBars = new FastRectangleRenderableSeries(wasmContext, {
...barOptions,
dataSeries: bandSeries,
fill: "#50C7E0CC",
stroke: "#50C7E0",
strokeThickness: 1,
topCornerRadius: 4
});
const bandPeaks = new FastRectangleRenderableSeries(wasmContext, {
...barOptions,
dataSeries: bandPeakSeries,
fill: "#F48420",
stroke: "#F48420",
strokeThickness: 1
});

// Hover to read a level, scroll to zoom, drag to pan, double-click to reset
const describe = (info) => {
const x = info.xValue;
const band = BANDS.find((b) => x >= b.low * 0.98 && x <= b.high);
const isBar = info.renderableSeries instanceof FastRectangleRenderableSeries;
const where = isBar && band ? `${band.name} Hz band` : `${x.toFixed(x < 100 ? 1 : 0)} Hz`;
// A bar's level is its top: read it from the band levels (the bars themselves start below the axis)
const bandIndex = BANDS.indexOf(band);
const level = isBar && band ? (info.renderableSeries === bandPeaks ? bandPeakLevels : bandLevels)[bandIndex] : info.yValue;
return `${info.seriesName}: ${where}, ${Number(level).toFixed(1)} dBFS`;
};
const legend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight });
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false, tooltipDataTemplate: (infos) => infos.map(describe) }),
legend,
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);

// State: { source, size, smoothing, peakHold, display: "fft" | "bands", logX }
let settings = null;
let configuredRate = 0;
let analyser = null;
let microphone = null;
let nextSample = null; // the test signal generator
let sampleRate = 48000;
const history = new Float32Array(MAX_SIZE); // the newest samples, oldest first
const block = new Float32Array(MAX_SIZE);
let frequencies, levels, peaks;
const bandLevels = new Float64Array(BANDS.length);
const bandPeakLevels = new Float64Array(BANDS.length);
// Leave a small gap between bars: shrink each band by 6% of its width at each end (in log terms)
const barStart = BANDS.map((b) => b.low * Math.pow(b.high / b.low, 0.06));
const barEnd = BANDS.map((b) => b.high / Math.pow(b.high / b.low, 0.06));

// All four series stay on the chart; show only the ones the current view needs, and list only those in the legend
const allSeries = [liveMountain, peakLine, bandBars, bandPeaks];
sciChartSurface.renderableSeries.add(...allSeries);
const setSeries = (list) => {
for (const rs of allSeries) {
rs.isVisible = list.includes(rs);
legend.includeSeries(rs, rs.isVisible);
}
};

// Apply new settings. Anything that changes the meaning of the averages or peaks starts them again.
const configure = (newSettings) => {
const old = settings ?? {};
settings = { ...newSettings };
const rateChanged = configuredRate !== sampleRate;
configuredRate = sampleRate;
if (settings.source !== "mic" && (settings.source !== old.source || rateChanged)) {
nextSample = createTestSignal(settings.source, sampleRate);
}
if (!analyser || analyser.size !== settings.size || settings.source !== old.source || rateChanged) {
analyser = createAnalyser(settings.size);
const bins = settings.size / 2 - 1;
frequencies = Float64Array.from({ length: bins }, (_, i) => ((i + 1) * sampleRate) / settings.size);
levels = new Float64Array(bins);
peaks = new Float64Array(bins).fill(-Infinity);
bandPeakLevels.fill(-Infinity);
}
if (!settings.peakHold || settings.display !== old.display) {
peaks.fill(-Infinity);
bandPeakLevels.fill(-Infinity);
}
if (settings.logX !== old.logX) {
const oldAxis = sciChartSurface.xAxes.get(0);
sciChartSurface.xAxes.remove(oldAxis, true);
sciChartSurface.xAxes.add(makeFrequencyAxis(settings.logX));
}
if (settings.logX !== old.logX || (settings.source === "close") !== (old.source === "close")) {
// Zoom in around 1 kHz for the two close tones, which are only a few pixels apart on the full range
sciChartSurface.xAxes.get(0).visibleRange =
settings.source === "close" ? new NumberRange(940, 1080) : settings.logX ? new NumberRange(20, 20000) : new NumberRange(0, 20000);
}
const fftView = settings.display === "fft";
setSeries(fftView ? (settings.peakHold ? [liveMountain, peakLine] : [liveMountain]) : settings.peakHold ? [bandBars, bandPeaks] : [bandBars]);
return { sampleRate, emptyBands: BANDS.filter((b) => Math.ceil(b.low / (sampleRate / settings.size)) > Math.ceil(b.high / (sampleRate / settings.size)) - 1) };
};

// One frame: take in the samples that "arrived" since the last frame, analyse the newest block and redraw
let lastTime = 0;
let owed = 0;
const frame = (now) => {
const size = settings.size;
if (microphone) {
microphone.read(history); // the newest MAX_SIZE samples
} else {
const seconds = lastTime ? Math.min((now - lastTime) / 1000, 0.1) : MAX_SIZE / sampleRate;
owed += seconds * sampleRate;
const count = Math.min(Math.floor(owed), MAX_SIZE);
owed -= Math.floor(owed);
history.copyWithin(0, count); // drop the oldest samples, append the new ones
for (let i = MAX_SIZE - count; i < MAX_SIZE; i++) history[i] = nextSample();
}
block.set(history.subarray(MAX_SIZE - size)); // the newest `size` samples
lastTime = now;
analyser.analyse(block, settings.smoothing);

if (settings.display === "fft") {
analyser.binLevels(levels);
liveSeries.clear();
liveSeries.appendRange(frequencies, levels);
if (settings.peakHold) {
for (let i = 0; i < levels.length; i++) peaks[i] = Math.max(peaks[i], levels[i]);
peakSeries.clear();
peakSeries.appendRange(frequencies, peaks);
}
} else {
analyser.bandLevels(sampleRate, bandLevels);
const x = [], x1 = [], y = [], y1 = [], px = [], px1 = [], py = [], py1 = [];
BANDS.forEach((band, b) => {
if (Number.isNaN(bandLevels[b])) return; // narrower than one FFT bin: nothing to show
x.push(barStart[b]);
x1.push(barEnd[b]);
y.push(FLOOR_DB - 100);
y1.push(bandLevels[b]);
bandPeakLevels[b] = Math.max(bandPeakLevels[b], bandLevels[b]);
px.push(barStart[b]);
px1.push(barEnd[b]);
py.push(bandPeakLevels[b] - 0.8);
py1.push(bandPeakLevels[b]);
});
bandSeries.clear();
bandSeries.appendRange(x, y, x1, y1);
if (settings.peakHold) {
bandPeakSeries.clear();
bandPeakSeries.appendRange(px, py, px1, py1);
}
}
};

// Animate with requestAnimationFrame at up to 30 updates a second, and stop when the chart is deleted
let handle = 0;
let lastDraw = 0;
const loop = (now) => {
if (sciChartSurface.isDeleted) return;
if (now - lastDraw >= 1000 / 30 - 2) {
lastDraw = now;
frame(now);
}
handle = requestAnimationFrame(loop);
};
const stopMicrophone = () => {
microphone?.stop();
microphone = null;
};
sciChartSurface.addDeletable({
delete: () => {
cancelAnimationFrame(handle);
stopMicrophone();
}
});

return {
start: (initialSettings) => {
const info = configure(initialSettings);
handle = requestAnimationFrame(loop);
return info;
},
configure,
// Switch to the microphone (call it from a click) or back to the test signals, then call configure()
useMicrophone: async (on) => {
if (on) {
const opened = await openMicrophone(MAX_SIZE); // throws if refused or not available
stopMicrophone();
microphone = opened;
sampleRate = opened.sampleRate;
} else {
stopMicrophone();
sampleRate = 48000;
}
history.fill(0);
}
};
}

Key points:

  • The spectrum is an XyDataSeries of frequencies and levels drawn by a FastMountainRenderableSeries, with a peak-hold FastLineRenderableSeries on top. For bands, a FastRectangleRenderableSeries with an XyxyDataSeries draws each bar from its lower to its upper band edge (EColumnMode.StartEnd), so the bars sit exactly on the band edges on a log axis.
  • A LogarithmicAxis with logBase: 10 gives one major gridline per decade (100 Hz, 1 kHz, 10 kHz) and minor gridlines at 2, 3, 4… times each. Swap it for a NumericAxis to get a linear frequency axis. Skip bin 0 (0 Hz): a log axis can't show it.
  • Animate with requestAnimationFrame, and update the series with clear() and appendRange() each frame. A fixed y-axis range (autoRange: EAutoRange.Never) stops the axis jumping. Register a delete callback with sciChartSurface.addDeletable() to stop the loop and release the microphone when the chart goes away.
  • For the microphone, getUserMedia works only in a secure context (HTTPS or localhost), and the browser asks the user's permission. Turn off echoCancellation, noiseSuppression and autoGainControl, which are meant for calls and reshape the spectrum. Inside an iframe on another site, the frame also needs allow="microphone".

Web Audio AnalyserNode or your own FFT?​

The browser's AnalyserNode (part of the Web Audio API) runs the FFT for you. Set fftSize (a power of 2 from 32 to 32,768) and smoothingTimeConstant (its exponential averaging, 0.8 by default), and getFloatFrequencyData() fills an array with one level in dB per bin. It's the fastest way to a live display. AnalyserNode fixes three things:

  • it always uses a Blackman window;
  • its levels are relative: a full-scale sine reads about −14 dB rather than 0 dBFS, because of the window's gain and the FFT's scaling, so add an offset if you need dBFS;
  • its smoothing is applied each time you call it, so the effective averaging time depends on how often you ask for data.

Your own FFT on getFloatTimeDomainData() (as in the JavaScript tab) gives you the window, the dB scaling, linear or exponential averaging, overlap, peak hold, bands and weighting. Use it when you need calibrated dBFS, bands or weighting.

See it in the demo app: JavaScript audio spectrum analyzer · React audio spectrum analyzer · Angular audio spectrum analyzer, which adds a waveform and a scrolling spectrogram to the spectrum. SciChart also has audio analyzer examples for Android, iOS and WPF.

Go deeper: SciChart.js logarithmic axis documentation, the mountain (area) series and rectangle series documentation, and the guides to the FFT, power spectral density and the spectrogram.

Frequently asked questions​

What is a spectrum analyzer used for?​

A spectrum analyzer is used to see which frequencies a signal contains and how strong each one is. In audio, that means balancing a mix with EQ, finding mains hum and feedback, measuring rooms, loudspeakers and headphones, and tracking machine noise. In radio and electronics, it checks transmitters, interference, harmonics and the noise floor of a circuit.

What does a spectrum analyzer measure?​

A spectrum analyzer measures the level of a signal at each frequency: amplitude or power on the vertical axis, frequency on the horizontal axis. From that display you read the frequency and level of tones and their harmonics, the noise floor, the bandwidth a signal occupies, and how the balance of low, mid and high frequencies changes over time.

What is the difference between a spectrum analyzer and an oscilloscope?​

An oscilloscope shows a signal's voltage against time: its waveform, timing, rise time and glitches. A spectrum analyzer shows the signal's level against frequency: which tones, harmonics and noise it contains. Use an oscilloscope to see when and what shape; use a spectrum analyzer to see which frequencies and how much. Many oscilloscopes have an FFT mode, but a dedicated analyzer usually has a lower noise floor and finer frequency resolution.

What is resolution bandwidth on a spectrum analyzer?​

Resolution bandwidth (RBW) is the width of the filter each point on the display measures through. Two tones closer together than about the RBW merge into one peak, and the displayed noise floor rises by 10 dB for every tenfold increase in RBW. In an FFT analyzer, the RBW is the bin width (sample rate divided by FFT size) times the window's noise bandwidth, about 1.5 bins for a Hann window.

Why does pink noise slope down on a spectrum analyzer?​

Pink noise has equal power in every octave, so its power per hertz falls by half (3 dB) each time the frequency doubles. An FFT analyzer's bins all have the same width in hertz, so pink noise slopes down at 3 dB per octave. An octave or 1/3-octave analyzer's bands get wider as frequency rises, which cancels the slope, so pink noise looks flat.

How do I make an audio spectrum analyzer in JavaScript?​

Get audio from the microphone with navigator.mediaDevices.getUserMedia on an HTTPS page, connect it to a Web Audio AnalyserNode, and call getFloatFrequencyData in a requestAnimationFrame loop to get one level in dB per frequency bin. For full control of the window, scaling and bands, read getFloatTimeDomainData and run your own FFT. Plot the levels against frequency on a logarithmic axis, for example with a SciChart.js LogarithmicAxis and a mountain series.

Sources​