Window Functions in Signal Processing
What is a window function?
A window function (also called a tapering function or apodization function) is a set of weights that you multiply a block of samples by before taking its FFT. It is largest in the middle and falls towards the ends, so the block starts and stops smoothly. This reduces spectral leakage, the smearing of one frequency across many FFT bins.

A strong tone that falls between FFT bins, a Hann window (top left), the window's own response (top right) and the spectrum in decibels with a weak tone 60 dB down (bottom), sample data. Try the interactive version, where you can switch windows, move the tone and the weak tone, and see the leakage change.
- The FFT assumes the record repeats. A tone that doesn't fit a whole number of cycles leaves a jump at the join, and that jump leaks energy into every bin.
- A window trades a wider main lobe (less resolution) for lower side lobes (less leakage). No window wins on both.
- Hann is the everyday default. Hamming has a lower first side lobe; Hann's side lobes fall away faster. Blackman and Blackman–Harris find weak tones; flat top measures amplitude.
- Windowing lowers every level: divide by the window's sum (its coherent gain) for tones, and use its equivalent noise bandwidth (ENBW) for noise and PSD.
- Zero padding doesn't fix leakage. It only draws the same leaky spectrum at more points.
What is spectral leakage?
The discrete Fourier transform, and the FFT that computes it, works on a block of samples, and it behaves as if that block were one period of a signal that repeats forever. Each bin is a sine wave that fits exactly whole cycles into the block.
- If a tone completes a whole number of cycles in the block, the copies join seamlessly, the tone matches one bin exactly, and every other bin reads zero.
- If it doesn't, say 4.5 cycles, the repeated signal has a jump at every join. A jump is a sharp edge, and a sharp edge contains energy at every frequency. So the tone's energy spreads into its neighbours and, more weakly, into bins far away.
That spreading is spectral leakage. It comes from cutting a finite record out of a longer one.
In real measurements a tone almost never fits the record exactly, because the record length is set by the FFT size, not by the signal. So leakage is the normal case, and it causes three problems:
- Hidden weak tones. The skirt of a strong peak can be higher than a small peak near it.
- Wrong peak heights. A tone halfway between two bins reads 3.92 dB low with no window. This is scalloping loss, named after the scalloped shape of the error as a tone moves between bins.
- A raised floor. Leakage from a large component, including a DC offset, lifts the apparent noise floor across the spectrum.
How a window function works
Before the FFT, each sample is multiplied by a weight . The weights are near 1 in the middle of the block and close to 0 at the ends, so the ends of the block, and the jump between copies, are squeezed down to almost nothing.
Multiplying two signals sample by sample convolves their spectra (the convolution theorem). So the spectrum you see is the true spectrum smeared by the window's own spectrum :
A pure tone's true spectrum is a single spike, so after windowing every tone shows up as a copy of centred on the tone's frequency. The FFT bins then sample that copy at whole-bin spacing. Everything about leakage follows from the shape of . Cutting out a block is itself a rectangular window, with every weight equal to 1.
A window's spectrum has two parts:
- The main lobe, the central peak. Its width decides resolution: two tones closer than about one main-lobe width merge into one peak. A tone that falls between bins is sampled partway down the main lobe, which is where scalloping loss comes from.
- The side lobes, the ripples either side. Their height decides leakage: a tone's side lobes land in other bins and can hide weaker tones there.
Tapering the ends harder lowers the side lobes but widens the main lobe. A window that is smooth at its ends also makes its side lobes fall away faster with distance: one with a jump in value (rectangular, Hamming) gives side lobes that fall by 6 dB per octave, and one that reaches zero smoothly (Hann, Blackman) gives 18 dB per octave.
Because Hann is a single cosine, windowing in time is the same as a three-point convolution of the unwindowed FFT: . You can apply a Hann window after the FFT, which is useful when you need both spectra.
The figures that describe a window
| Figure | What it means | Why it matters |
|---|---|---|
| Highest side lobe | The tallest ripple outside the main lobe, in dB below the peak | How far below a strong tone a weak one can be and still be seen near it |
| Side-lobe roll-off | How quickly the side lobes fall with distance, in dB per octave | Whether leakage is still a problem far from a strong tone |
| −3 dB and −6 dB width | The main lobe's width, in bins, at those levels below its peak | Resolution: two equal tones separate when they are further apart than about the −6 dB width |
| Coherent gain | The window's average value, | How much the window lowers a tone's peak; divide by it to correct amplitudes |
| Equivalent noise bandwidth (ENBW) | , in bins | How many bins wide each bin is for noise; it raises the noise floor by dB |
| Scalloping loss | How far a tone exactly halfway between bins reads below its true level | The worst-case amplitude error from where a tone falls |
Window function formulas
The common windows are all cosine sums. For :
| Window | |||||
|---|---|---|---|---|---|
| Rectangular (no window) | 1 | ||||
| Hann | 0.5 | 0.5 | |||
| Hamming | 0.54 | 0.46 | |||
| Blackman | 0.42 | 0.5 | 0.08 | ||
| Blackman–Harris (4-term) | 0.35875 | 0.48829 | 0.14128 | 0.01168 | |
| Flat top (5-term) | 0.21557895 | 0.41663158 | 0.277263158 | 0.083578947 | 0.006947368 |
Written out, the three classics are:
A few notes on the names:
- Hann takes its name from Julius von Hann, an Austrian meteorologist. Many people call it the Hanning window, because Blackman and Tukey used "hanning" as a verb for applying it; both names mean the same window.
- Hamming is named after Richard Hamming. Its coefficients are chosen to cancel the first side lobe: the exact value is , usually rounded to 0.54.
- Blackman–Harris is one of a family of cosine sums with three or four terms, published by Harris (1978) and refined by Nuttall (1981). The 4-term version above keeps its side lobes 92 dB down.
- Flat-top windows are designed so the top of the main lobe is almost flat, not for low leakage. Several exist; the 5-term one above is the one most signal-processing libraries call "flattop". Its values dip slightly below zero near the ends.
Symmetric vs periodic windows
The formulas above divide by . That makes the window periodic (also called DFT-even): it is one period of a repeating cosine, so the sample after the last one would be the first one again. For an FFT, that's what you want, because the FFT treats the block as periodic too, and it gives the exact figures in the table below.
The symmetric form divides by instead, so the first and last samples are equal and the window is a mirror image about its centre. Use it to design FIR filters, where symmetry gives the filter linear phase.
The difference is one sample's worth of stretch, which only matters for short windows. Check which one a library gives you: numpy.hanning(N) and MATLAB's hann(N) are symmetric, while scipy.signal.get_window('hann', N) and hann(N, 'periodic') are periodic. The FFT guide explains why mixing them up makes spectra disagree.
Window functions compared: measured figures
We measured every figure in this table with the window and FFT code in the live example, using periodic windows of 1,024 samples and a finely zero-padded transform. They agree closely with the values Harris (1978) published; small differences in the second decimal place come from how each width is measured. Widths are in bins.
| Window | Highest side lobe | Side-lobe roll-off | −3 dB width | −6 dB width | First nulls | Coherent gain | ENBW | Scalloping loss |
|---|---|---|---|---|---|---|---|---|
| Rectangular | −13.3 dB | −6 dB/octave | 0.89 | 1.21 | ±1 | 1.00 | 1.00 | 3.92 dB |
| Hann | −31.5 dB | −18 dB/octave | 1.44 | 2.00 | ±2 | 0.50 | 1.50 | 1.42 dB |
| Hamming | −42.7 dB | −6 dB/octave | 1.30 | 1.82 | ±2 | 0.54 | 1.36 | 1.75 dB |
| Blackman | −58.1 dB | −18 dB/octave | 1.64 | 2.30 | ±3 | 0.42 | 1.73 | 1.10 dB |
| Blackman–Harris (4-term) | −92.0 dB | −6 dB/octave | 1.90 | 2.67 | ±4 | 0.36 | 2.00 | 0.83 dB |
| Flat top (5-term) | −93.0 dB | −6 dB/octave | 3.72 | 4.58 | ±5 | 0.22 | 3.77 | 0.01 dB |
How to read it:
- Down the side-lobe column, leakage falls; down the width columns, resolution gets worse. Every row pays for lower side lobes with a wider main lobe.
- Main-lobe width in radians: the first nulls at ±2 bins mean Hann's and Hamming's main lobes are 4 bins, or radians per sample, wide. Rectangular's is and Blackman's .
- Worst-case loss: for a tone halfway between bins buried in noise, the scalloping loss and the noise-bandwidth penalty add up to about 3.9 dB for rectangular, 3.2 dB for Hann, 3.1 dB for Hamming and 3.5 dB for Blackman, which makes Hann and Hamming popular for detecting tones in noise.
Worked example: can you see a tone 60 dB weaker?
With 1,024 samples, a strong tone at bin 40.5 (the worst place for it) and very low noise, we added a tone 60 dB weaker and checked whether it stood above everything around it:
| Weak tone is… | Rectangular | Hann | Hamming | Blackman | Blackman–Harris | Flat top |
|---|---|---|---|---|---|---|
| 5 bins away | Hidden | Hidden | Hidden | Hidden | Visible, by 40 dB | Visible, by 45 dB |
| 12 bins away | Hidden | Visible, by 13 dB | Hidden | Visible, by 22 dB | Visible, by 42 dB | Visible, by 39 dB |
| 20 bins away | Hidden | Visible, by 27 dB | Hidden | Visible, by 35 dB | Visible, by 62 dB | Visible, by 36 dB |
Hamming never shows it: its side lobes start lower than Hann's but stay in the −40s and −50s of dB for dozens of bins. Hann's start higher but fall away, so by 12 bins they are lower than Hamming's.
Hann vs Hamming window
The two are the same shape, a raised cosine, with slightly different heights:
| Hann (Hanning) | Hamming | |
|---|---|---|
| Formula | ||
| Value at the ends | 0 | 0.08 |
| Highest side lobe | −31.5 dB, the first one | −42.7 dB; the first is almost cancelled |
| Side-lobe roll-off | −18 dB per octave | −6 dB per octave |
| Main lobe, first nulls | ±2 bins | ±2 bins |
| ENBW | 1.50 bins | 1.36 bins |
| Scalloping loss | 1.42 dB | 1.75 dB |
| Typical use | General spectrum analysis, noise, PSD, vibration | Speech and audio frames; FIR filter design; interference close to a tone |
Hann goes all the way to zero at the ends, so the windowed record has no jump in value or slope and its side lobes fall away fast. Hamming stops at 0.08, a small step, and in return its constant and cosine terms are balanced so the first side lobe almost cancels. The leftover step is why its side lobes barely fall.
Choose Hamming when the interference you care about is within a few bins of a strong tone, and Hann when it could be anywhere in the spectrum, or when you're measuring noise. If you're unsure, Hann is the safer default.
Which window should you use?
Use Hann for most work, and switch only when you need accurate amplitudes, deeper side lobes or a transient that fits the block.
| If you need to… | Use | Why |
|---|---|---|
| Analyse a signal you know little about | Hann | A good balance of resolution, leakage and noise bandwidth |
| Separate two tones of similar size that are close together | Hann or Hamming (rectangular if they fit the record exactly) | The narrowest main lobes after rectangular |
| Find a weak tone near a strong one | Blackman, or Blackman–Harris for 60 dB or more | Side lobes 58 dB and 92 dB down |
| Measure a tone's amplitude accurately, such as calibrating against a reference | Flat top | Reads within 0.01 dB wherever the tone falls between bins |
| Measure noise, random vibration or a power spectral density | Hann, with 50% overlap between segments | Low leakage, and overlap recovers the samples the taper discards |
| Measure a transient that starts and ends inside the record, such as an impact | Rectangular (no window) | Tapering would cut off part of the event |
| Analyse a tone that you sample synchronously, an exact number of cycles per record | Rectangular | There is no jump, so there is no leakage to fix |
| Frame speech or audio for a short-time FFT or spectrogram | Hann or Hamming | The usual choices; Hann with 50% overlap sums to a constant |
Two tones of equal size show as separate peaks when they are further apart than about the window's −6 dB width: about 1.2 bins with no window, 2 bins with Hann and 2.3 with Blackman. If they're closer than that, no window will separate them: record for longer.
Correcting amplitude and power after windowing
A window removes part of the signal, so every level in a windowed spectrum reads low. How you correct depends on what you are measuring.
- Tones (amplitude correction): a tone's peak is scaled by the window's coherent gain, its average value. Divide each FFT magnitude by instead of (and double every bin except 0 and for a one-sided spectrum), and a tone centred on a bin reads its true amplitude. The correction factor is : 2.00 for Hann, 1.85 for Hamming, 2.38 for Blackman, 2.79 for Blackman–Harris and 4.64 for flat top.
- Noise and broadband signals (power correction): noise is spread across all bins, so it is scaled by the window's average power, , not its average value. Correct RMS levels by : 1.63 for Hann, 1.59 for Hamming, 1.81 for Blackman. A power spectral density builds this in by dividing by , which is the same as dividing by the ENBW in hertz.
You can't have both in one plot. With amplitude correction, a tone reads correctly but the noise floor reads high by : 1.76 dB for Hann, 5.76 dB for flat top. With power correction, the noise reads correctly but tones read low. Label which one a chart uses.
Scalloping loss is a separate error. Even with the right correction, a tone between bins reads low by up to the scalloping loss (1.42 dB for Hann), so test equipment offers a flat-top window for amplitude measurements. Its main lobe is so flat that the error is about 0.01 dB, but it is nearly 4 bins wide at −3 dB and raises the noise floor by 5.8 dB, so it's a poor choice for resolving close tones or finding weak ones. The alternative is to keep a narrower window and interpolate the peak from the bins either side of it.
Window functions in FIR filter design
An ideal low-pass filter's impulse response is a sinc function, which goes on forever in both directions. To make a real FIR filter, you keep samples of it and multiply them by a window: the windowed-sinc method.
The same trade-off applies, now to the filter's frequency response. Cutting the sinc off abruptly (a rectangular window) leaves ripples only about 21 dB down in the stopband, whatever the length. A tapering window lowers them: about 53 dB with Hamming and 74 dB with Blackman, at the cost of a wider transition band. For filter design, use the symmetric form of the window, dividing by (the number of taps minus one), so the filter has linear phase.
The FIR vs IIR filters guide works through the windowed-sinc method step by step, with a live demo where you can switch the window and watch the stopband change. Other uses of windows include overlap-add processing, where overlapping Hann windows sum to a constant, and smoothing the edges of audio clips to avoid clicks.
Does zero padding reduce spectral leakage?
No. Zero padding, appending zeros to the record before the FFT, gives you more bins, closer together. They are samples of the same windowed spectrum, main lobe, side lobes and all. So zero padding:
- draws the leakage in more detail, which can make it look worse, because the side lobes that fell between bins are now visible;
- reduces the apparent scalloping loss, because a bin lands nearer the top of each peak;
- doesn't separate close tones, because the main lobe is as wide as ever.
Only a window lowers the side lobes, and only a longer record narrows the main lobe. See zero padding in the FFT guide for more.
Common windowing mistakes
Most windowing mistakes are forgetting to window, or forgetting to correct for the window afterwards.
- Using no window by accident. Taking the FFT of a raw block applies a rectangular window, with side lobes only 13 dB down. Unless the signal fits the block exactly or is a transient, apply Hann at least.
- Forgetting to correct the level. Hann alone lowers every tone by 6 dB. Divide by the window's sum, not by .
- Correcting noise with the tone factor. Amplitude correction makes noise read high by the ENBW. Use power correction, or a PSD, for noise.
- Using a symmetric window for the FFT. It makes small, confusing errors in short FFTs. Use the periodic form for spectrum analysis and the symmetric form for filter design.
- Choosing Hamming to find weak tones far away. Its side lobes barely fall. Use Hann or Blackman.
- Windowing a transient. An impact or pulse that sits inside the record is already zero at both ends; a window just attenuates or cuts it off.
- Windowing without overlap when averaging. With Hann and no overlap, the samples near each segment's ends barely count. Overlap segments by 50% (see Welch's method).
How to apply a window function in JavaScript, React or Angular
The demo windows a record of one or two tones (1,024 samples by default), takes its FFT and redraws all three charts each time you move a control. It runs the windows and the FFT in your browser with the plain JavaScript functions in the code. The top left chart shows the record (blue), the window (yellow) and the windowed record (orange); the top right chart shows the window's own frequency response; the bottom chart shows the spectrum in dB, with the strong tone's leakage on its own as a dashed line.
Choose a window, move the tone from bin 40.0 (on a bin, no leakage) to 40.5 (halfway, worst case), switch the weak tone 60 dB down on or off and move its offset, and change the FFT size and the noise. The readout gives the peak's error, the highest side lobe, the ENBW, the coherent gain and whether the weak tone can be seen. Hover over the spectrum to read a side lobe's level; scroll to zoom, drag to pan and double-click to reset.
Here is the code for this example. The JavaScript tab includes the FFT, the window functions and the spectrum code; the React and Angular tabs reuse them to plot a Hann-windowed spectrum.
- JavaScript
- React
- Angular
// Spectral leakage explorer: one strong tone, an optional weak tone and noise, windowed and transformed with an FFT,
// in JavaScript with SciChart.js. The FFT and window functions below are plain JavaScript with no dependencies.
// 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 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;
}
}
}
}
// Every window here is a cosine sum: w[i] = a0 - a1 cos(x) + a2 cos(2x) - a3 cos(3x) + a4 cos(4x),
// with x = 2 pi i / N (periodic form, for spectrum analysis) or 2 pi i / (N - 1) (symmetric form, for filter design).
const WINDOW_COEFFICIENTS = {
rectangular: [1],
hann: [0.5, 0.5],
hamming: [0.54, 0.46],
blackman: [0.42, 0.5, 0.08],
blackmanHarris: [0.35875, 0.48829, 0.14128, 0.01168], // 4-term, -92 dB side lobes
flatTop: [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368] // 5-term flat top
};
function makeWindow(type, n, symmetric = false) {
const a = WINDOW_COEFFICIENTS[type];
const w = new Float64Array(n);
const period = symmetric ? n - 1 : n;
for (let i = 0; i < n; i++) {
let sum = 0;
for (let k = 0; k < a.length; k++) sum += (k % 2 === 0 ? 1 : -1) * a[k] * Math.cos((2 * Math.PI * k * i) / period);
w[i] = sum;
}
return w;
}
// Figures of merit: coherent gain (the window's mean, which scales a tone's peak) and equivalent noise bandwidth
// (how many bins wide the window's filter is for noise; 1 for rectangular, 1.5 for Hann)
function windowFigures(w) {
let sum = 0;
let sumSquares = 0;
for (const v of w) {
sum += v;
sumSquares += v * v;
}
return { coherentGain: sum / w.length, enbwBins: (w.length * sumSquares) / (sum * sum) };
}
// One-sided amplitude spectrum in dB: window, FFT, and divide by the window's sum so a tone of amplitude A
// centred on a bin reads 20 log10(A). Bin k is at k cycles per record.
function spectrumDb(samples, w) {
const n = samples.length;
const re = new Float64Array(n);
const im = new Float64Array(n);
let windowSum = 0;
for (let i = 0; i < n; i++) {
re[i] = samples[i] * w[i];
windowSum += w[i];
}
fft(re, im);
const bins = n / 2 + 1;
const levels = new Float64Array(bins);
for (let k = 0; k < bins; k++) {
const oneSided = k === 0 || k === n / 2 ? 1 : 2;
levels[k] = 20 * Math.log10(Math.max((oneSided * Math.hypot(re[k], im[k])) / windowSum, 1e-12)); // floor at -240 dB
}
return levels;
}
// The window's own frequency response: zero pad it 16 times so the main lobe and side lobes are drawn smoothly.
// Returns dB relative to the peak, from -spanBins to +spanBins, and the highest side lobe.
function windowResponse(type, spanBins) {
const length = 1024;
const pad = 16;
const size = length * pad;
const re = new Float64Array(size);
const im = new Float64Array(size);
re.set(makeWindow(type, length));
fft(re, im);
const peak = Math.hypot(re[0], im[0]);
const half = spanBins * pad;
const offsets = [];
const levels = [];
for (let k = -half; k <= half; k++) {
const index = (k + size) % size; // negative frequencies wrap to the end of the FFT
offsets.push(k / pad);
levels.push(20 * Math.log10(Math.max(Math.hypot(re[index], im[index]) / peak, 1e-12)));
}
// Highest side lobe: the largest level beyond the first null (the first dip below -20 dB that turns back up;
// a flat-top window's main lobe ripples near 0 dB, so a plain "first minimum" would stop too early)
let i = half + 1;
while (i < levels.length - 1 && (levels[i] > -20 || levels[i + 1] < levels[i])) i++;
let highestSideLobe = -Infinity;
for (; i < levels.length; i++) highestSideLobe = Math.max(highestSideLobe, levels[i]);
return { offsets, levels, highestSideLobe };
}
// Test signal: a strong tone (amplitude 1, 0 dB), an optional weak tone (amplitude 0.001, -60 dB) and seeded noise.
// Frequencies are in bins (cycles per record), so 40.0 fits the record exactly and 40.5 is the worst case.
function makeSignal(n, toneBins, weakOn, weakOffsetBins, noiseRms) {
let seed = 7;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
const strong = new Float64Array(n);
const values = new Float64Array(n);
for (let i = 0; i < n; i++) {
strong[i] = Math.sin((2 * Math.PI * toneBins * i) / n + 0.3);
const weak = weakOn ? 0.001 * Math.sin((2 * Math.PI * (toneBins + weakOffsetBins) * i) / n) : 0;
const noise = (random() + random() + random() + random() + random() + random() - 3) * Math.SQRT2 * noiseRms; // about Gaussian
values[i] = strong[i] + weak + noise;
}
return { strong, values };
}
async function createLeakageCharts(timeDiv, responseDiv, spectrumDiv) {
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const zoomModifiers = () => [
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
];
// Top left: the record, the window and the windowed record
const timeChart = await SciChartSurface.create(timeDiv, { theme: new SciChartJsNavyTheme() });
const timeSurface = timeChart.sciChartSurface;
const timeXAxis = new NumericAxis(timeChart.wasmContext, { axisTitle: "Sample", labelPrecision: 0 });
timeSurface.xAxes.add(timeXAxis);
timeSurface.yAxes.add(
new NumericAxis(timeChart.wasmContext, { autoRange: EAutoRange.Never, visibleRange: new NumberRange(-1.25, 1.25), labelPrecision: 1 })
);
const signalSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Signal", dataIsSortedInX: true });
const windowSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Window", dataIsSortedInX: true });
const windowedSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Windowed", dataIsSortedInX: true });
timeSurface.renderableSeries.add(
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: signalSeries, stroke: "#50C7E066" }),
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: windowedSeries, stroke: "#F48420" }),
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: windowSeries, stroke: "#FFD866", strokeThickness: 3 })
);
timeSurface.chartModifiers.add(new LegendModifier({ showCheckboxes: false }), ...zoomModifiers());
// Top right: the window's own frequency response (main lobe and side lobes)
const responseChart = await SciChartSurface.create(responseDiv, { theme: new SciChartJsNavyTheme() });
const responseSurface = responseChart.sciChartSurface;
responseSurface.xAxes.add(
new NumericAxis(responseChart.wasmContext, { axisTitle: "Bins from the tone", labelPrecision: 0 })
);
responseSurface.yAxes.add(
new NumericAxis(responseChart.wasmContext, { autoRange: EAutoRange.Never, visibleRange: new NumberRange(-140, 5), labelPrecision: 0 })
);
const responseSeries = new XyDataSeries(responseChart.wasmContext, { dataSeriesName: "Window response (dB)", dataIsSortedInX: true });
responseSurface.renderableSeries.add(
new FastLineRenderableSeries(responseChart.wasmContext, { dataSeries: responseSeries, stroke: "#FFD866", strokeThickness: 2 })
);
responseSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: false }),
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (infos) => infos.map((info) => `${info.formattedXValue} bins: ${info.formattedYValue} dB`)
}),
...zoomModifiers()
);
// Bottom: the spectrum in dB, so leakage skirts and the weak tone are both visible
const spectrumChart = await SciChartSurface.create(spectrumDiv, { theme: new SciChartJsNavyTheme() });
const spectrumSurface = spectrumChart.sciChartSurface;
const spectrumXAxis = new NumericAxis(spectrumChart.wasmContext, { axisTitle: "Frequency (bins)", labelPrecision: 0 });
spectrumSurface.xAxes.add(spectrumXAxis);
spectrumSurface.yAxes.add(
new NumericAxis(spectrumChart.wasmContext, {
axisTitle: "Amplitude (dB)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-160, 5),
labelPrecision: 0
})
);
const spectrumSeries = new XyDataSeries(spectrumChart.wasmContext, { dataSeriesName: "Spectrum", dataIsSortedInX: true });
const leakageSeries = new XyDataSeries(spectrumChart.wasmContext, { dataSeriesName: "Strong tone alone", dataIsSortedInX: true });
spectrumSurface.renderableSeries.add(
new FastLineRenderableSeries(spectrumChart.wasmContext, { dataSeries: leakageSeries, stroke: "#F4842088", strokeDashArray: [4, 4] }),
new FastLineRenderableSeries(spectrumChart.wasmContext, { dataSeries: spectrumSeries, stroke: "#50C7E0", strokeThickness: 2 })
);
spectrumSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (infos) => infos.map((info) => `Bin ${info.formattedXValue}: ${info.formattedYValue} dB`)
}),
...zoomModifiers()
);
// Recompute everything from the settings: { windowType, toneBins, weakOn, weakOffsetBins, size, noiseRms }
const update = (s) => {
const w = makeWindow(s.windowType, s.size);
const { strong, values } = makeSignal(s.size, s.toneBins, s.weakOn, s.weakOffsetBins, s.noiseRms);
const index = Array.from({ length: s.size }, (_, i) => i);
signalSeries.clear();
signalSeries.appendRange(index, values);
windowSeries.clear();
windowSeries.appendRange(index, Array.from(w));
windowedSeries.clear();
windowedSeries.appendRange(index, values.map((v, i) => v * w[i]));
timeXAxis.visibleRange = new NumberRange(0, s.size - 1);
const levels = spectrumDb(values, w);
const leakage = spectrumDb(strong, w); // the strong tone on its own: what can hide the weak one
const background = spectrumDb(makeSignal(s.size, s.toneBins, false, 0, s.noiseRms).values, w); // everything but the weak tone
const bins = Array.from({ length: levels.length }, (_, k) => k);
spectrumSeries.clear();
spectrumSeries.appendRange(bins, Array.from(levels));
leakageSeries.clear();
leakageSeries.appendRange(bins, Array.from(leakage));
spectrumXAxis.visibleRange = new NumberRange(Math.max(0, s.toneBins - 30), Math.min(s.size / 2, s.toneBins + 40));
const response = windowResponse(s.windowType, 16);
responseSeries.clear();
responseSeries.appendRange(response.offsets, response.levels);
// Readout: how far the peak reads below the true 0 dB, and how far the weak tone stands above the leakage
const k0 = Math.round(s.toneBins);
const peakDb = Math.max(leakage[k0 - 1], leakage[k0], leakage[k0 + 1]);
const weakBin = Math.round(s.toneBins + s.weakOffsetBins);
return {
peakErrorDb: peakDb,
highestSideLobeDb: response.highestSideLobe,
...windowFigures(w),
weakMarginDb: levels[weakBin] - background[weakBin]
};
};
return { update };
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} from "scichart";
// fft, makeWindow and spectrumDb: copy them from the JavaScript tab
import { makeWindow, spectrumDb } from "./windows";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Frequency (Hz)" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Amplitude (dB)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-140, 5)
})
);
// Your block of samples (a power of 2 long) and its sample rate
const { samples, sampleRate } = getYourSamples();
const levels = spectrumDb(samples, makeWindow("hann", samples.length)); // or "blackman", "flatTop"...
const frequencies = Array.from(levels, (_, k) => (k * sampleRate) / samples.length);
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: frequencies, yValues: Array.from(levels), dataIsSortedInX: true }),
stroke: "#50C7E0",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
return { sciChartSurface };
};
export const WindowedSpectrum = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} from "scichart";
// fft, makeWindow and spectrumDb: copy them from the JavaScript tab
import { makeWindow, spectrumDb } from "./windows";
@Component({
selector: "app-windowed-spectrum",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class WindowedSpectrumComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Frequency (Hz)" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Amplitude (dB)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-140, 5)
})
);
// Your block of samples (a power of 2 long) and its sample rate
const { samples, sampleRate } = getYourSamples();
const levels = spectrumDb(samples, makeWindow("hann", samples.length)); // or "blackman", "flatTop"...
const frequencies = Array.from(levels, (_, k) => (k * sampleRate) / samples.length);
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: frequencies, yValues: Array.from(levels), dataIsSortedInX: true }),
stroke: "#50C7E0",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
return { sciChartSurface };
};
}
Key points:
- One function makes every window:
makeWindowevaluates the cosine sum from a table of coefficients; passsymmetric = truefor FIR filter design.windowFigurescomputes the coherent gain and ENBW from the weights, so you can check any window you add. spectrumDbdivides by the window's sum, so a tone centred on a bin reads its true level in dB whichever window you use.- Each spectrum is an
XyDataSeriesdrawn by aFastLineRenderableSeries, withdataIsSortedInX: truebecause bins are in order. The example'supdate()callsclear()andappendRange()whenever a control moves, and SciChart.js redraws on the next frame. - A fixed dB range (
autoRange: EAutoRange.Neverwith avisibleRange) keeps the axis still while you compare windows, so side lobes and the noise floor can be compared by eye.
See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart, which runs an FFT on live microphone input.
Go deeper: SciChart.js line series documentation, and the FFT guide for bins, resolution and how to read a spectrum.
Frequently asked questions
What is a window function in signal processing?
A window function is a set of weights, one per sample, that you multiply a block of samples by before an FFT or when designing an FIR filter. It is largest in the middle and tapers towards the ends, so the block has no sudden jump where it starts and stops. That reduces spectral leakage: energy from one frequency spreading into many others.
What is the difference between a Hann and a Hamming window?
Both are raised cosines. Hann is 0.5 - 0.5 cos(2 pi n / N) and falls to zero at the ends; Hamming is 0.54 - 0.46 cos(2 pi n / N) and stops at 0.08. Hamming's highest side lobe is lower, about -43 dB against Hann's -31.5 dB, but its side lobes stay near that level, while Hann's fall by 18 dB per octave. Use Hamming when interference is close to the tone, and Hann when it is far away or for noise.
Why does a window function reduce spectral leakage?
The FFT treats a block of samples as if it repeated forever. Unless a tone fits a whole number of cycles in the block, the repeat has a jump at the join, and a jump contains energy at every frequency. A window brings both ends of the block smoothly to (or near) zero, so the jump disappears and much less energy leaks into distant bins. The cost is a wider peak.
Which window function is best for an FFT?
Hann is the usual default for general analysis, noise and power spectral density. Use Blackman or Blackman-Harris to find a weak tone next to a strong one, a flat-top window to measure a tone's amplitude accurately, and no window (rectangular) for transients that start and end inside the block or tones that fit it exactly.
What is the main lobe width and side lobe level of a Hamming window?
A Hamming window's main lobe is 4 bins wide between its first nulls, which is 8 pi / N radians per sample, twice the width of no window. It is 1.30 bins wide at -3 dB and 1.82 bins at -6 dB. The first side lobe is almost cancelled (-44 dB), so the highest is a later one, at -42.7 dB, usually quoted as -43 dB. In FIR filter design it gives a stopband attenuation of about 53 dB.
How do I apply a window function in JavaScript?
Build an array of weights, for example w[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / N) for Hann, multiply each sample by its weight, run the FFT, and divide each magnitude by the sum of the weights (doubling all but the first and last bins) to read amplitudes. To plot the spectrum with SciChart.js, put the frequencies and levels in an XyDataSeries and draw them with a FastLineRenderableSeries.
Sources
- Harris, F. J. (1978), On the Use of Windows for Harmonic Analysis with the Discrete Fourier Transform. Proceedings of the IEEE, 66(1), 51–83. The standard reference for window figures of merit: side lobes, roll-off, bandwidths, coherent gain, ENBW and scalloping loss; the Blackman–Harris windows.
- Nuttall, A. H. (1981), Some Windows with Very Good Sidelobe Behavior. IEEE Transactions on Acoustics, Speech, and Signal Processing, 29(1), 84–91. Cosine-sum windows and their side-lobe roll-off.
- Heinzel, G., Rüdiger, A. and Schilling, R. (2002), Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows. Max Planck Institute for Gravitational Physics. Amplitude and power scaling, ENBW and flat-top windows.
- Blackman, R. B. and Tukey, J. W. (1958), The Measurement of Power Spectra from the Point of View of Communications Engineering, Part I and Part II. Bell System Technical Journal, 37(1), 185–282, and 37(2), 485–569; reprinted as a book by Dover, 1959. The origin of "hanning" and "hamming".
- Smith, S. W., The Scientist and Engineer's Guide to Digital Signal Processing: chapter 9, Applications of the DFT (spectral analysis and windows) and chapter 16, Windowed-Sinc Filters.
- Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. FIR filter design by windowing, and the windows' stopband attenuation.
- Smith, J. O., Spectral Audio Signal Processing, Center for Computer Research in Music and Acoustics (CCRMA), Stanford University. Windows and spectrum analysis in depth.