FFT (Fast Fourier Transform)
What is an FFT?
The FFT (fast Fourier transform) is an algorithm that splits a block of signal samples into the sine waves it contains, and measures how strong each frequency is. It computes the discrete Fourier transform (DFT) far faster than the direct method, which is why spectrum analysers, audio tools and vibration monitors can show a signal's frequencies in real time.

A test signal of three tones plus noise (top) and its FFT spectrum in decibels (bottom), sample data. Try the interactive version, where you can move a tone between bins and change the window.
- An FFT turns samples into frequency bins spaced apart, from 0 Hz up to the Nyquist frequency .
- It gives the same answer as the DFT, in about operations instead of .
- Longer records, finer detail: halving the bin width means recording for twice as long.
- A tone that falls between bins spreads into its neighbours (spectral leakage). A window such as Hann reduces it.
- Zero padding makes the plot smoother but doesn't separate tones that are too close together.
How the FFT works
This section explains the algorithm. To read a spectrum first, skip to how to read an FFT plot.
The Fourier transform says that any signal can be built from sine waves of different frequencies, amplitudes and phases. (For the idea itself, see the Fourier transform guide.) A computer works with a list of samples, so it uses the discrete Fourier transform. For samples , bin of the DFT is:
Each bin compares the signal with a sine and cosine that complete exactly cycles in the block. A strong match gives a large ; no match gives a value near zero.
Done directly, each of the bins needs multiplications, so the work grows as . Double the block and the work goes up four times.
The radix-2 trick
The FFT avoids most of that work by reusing it. Its best-known form, the radix-2 version of the algorithm James Cooley and John Tukey published in 1965 (Gauss had used the same idea around 1805, unpublished in his lifetime), works on blocks whose length is a power of 2:
- Split the samples into the even-numbered ones and the odd-numbered ones.
- Transform each half. Each is a DFT of half the length, and each of those splits again, down to blocks of one sample.
- Combine each pair of half-size results with a butterfly: two outputs, and , where is a fixed complex number called a twiddle factor.
The split only reorders the samples. Splitting into even and odd samples, then splitting each half the same way, ends with the samples in bit-reversed order: write each position as a binary number, read the bits backwards, and that's the sample that lands there. In a 16-sample block, position 1 (0001) gets sample 8 (1000). Code does the whole split in one pass, swapping pairs of samples in place.
Adapted from Burnett-Thompson (2007).
The DFT of one sample is that sample, so transforming a single sample costs nothing and the reordered list is already one-point spectra. All the work is in combining them.
Each butterfly multiplies the lower of its two values by a twiddle factor and outputs their sum and their difference:
Adapted from Burnett-Thompson (2007).
The twiddle factors are the DFT's own test waves, points spaced evenly around the unit circle. The FFT computes each product once and uses it twice, once added and once subtracted, and that reuse is where the saving comes from. Stage 1 pairs values next to each other, stage 2 pairs values 2 apart, stage 3 pairs values 4 apart, and so on, doubling until one -point spectrum is left.
Worked example: an 8-point FFT
Sample one cycle of a sine wave 8 times, , which gives .
Adapted from Burnett-Thompson (2007).
- Reorder. In bit-reversed order () the input is .
- Stage 1 combines neighbours with , so each pair becomes its sum and its difference: . These are four 2-point spectra.
- Stage 2 combines values 2 apart with and . The second butterfly, for example, takes and and gives and . The result is two 4-point spectra, and .
- Stage 3 combines values 4 apart with to . Bin 1 is , and bin 5, the same butterfly's difference, is . Bin 7 is .
The output comes out in natural order and is zero everywhere except and : one wave at one cycle per block, plus its mirror image in bin . Its amplitude is , and the marks a sine rather than a cosine. A direct DFT gives the same eight numbers with 64 multiplications; the FFT used 12 butterflies.
There are levels of splitting and butterflies per level, so the total work grows as rather than . The table below counts butterflies, each one complex multiplication, so its last column is about twice the ratio (102 times for 1,024 samples). The answer is the same as the direct DFT. If anything, the FFT's rounding errors are smaller, because each result passes through fewer operations.
| Block size | Direct DFT ( multiplications) | Radix-2 FFT ( butterflies) | About how many times less work |
|---|---|---|---|
| 256 | 65,536 | 1,024 | 64 |
| 1,024 | 1,048,576 | 5,120 | 200 |
| 4,096 | 16,777,216 | 24,576 | 680 |
| 65,536 | 4,294,967,296 | 524,288 | 8,200 |
| 1,048,576 | about 1.1 trillion | 10,485,760 | 100,000 |
The FFT made spectrum analysis cheap enough to run continuously, on everything from lab instruments to phones. Other FFT algorithms (mixed-radix, split-radix, Bluestein's) handle block sizes that aren't powers of 2, and FFT libraries pick between them for you.
The inverse FFT
The inverse DFT differs from the forward one only in the sign of the exponent and a factor of . So the same FFT code can run it backwards, in four steps:
- Conjugate the spectrum: flip the sign of every imaginary part.
- Run the forward FFT on the result.
- Divide every output by .
- Conjugate again. For a real signal the imaginary parts left over are zero, apart from rounding errors.
It works because conjugating the input and the output of a sum of complex exponentials flips the sign of the exponent: . Put the spectrum from the 8-point example through these steps and the eight sine samples come back. Some texts and libraries put the on the forward transform instead of the inverse, so check which convention a library uses before comparing amplitudes.
How to read an FFT plot
An FFT plot (also called an FFT spectrum or FFT graph) has frequency along the horizontal axis and amplitude or level up the vertical axis. Each peak is a frequency the signal contains; its height is how strong that frequency is.
Read it in this order:
- Check the frequency axis. It runs from 0 Hz to the Nyquist frequency, half the sample rate (). Nothing above that can be measured; it would have shown up as a false, lower frequency (aliasing) when the signal was sampled.
- Check the vertical scale. On a linear scale, a peak's height is the tone's amplitude. On a decibel (dB) scale, each 20 dB is a factor of 10 in amplitude: , so amplitude 1 is 0 dB, 0.5 is about -6 dB, 0.1 is -20 dB and 0.001 is -60 dB. Use dB when you need to see weak tones next to strong ones.
- Find the peaks. Each narrow peak is a steady tone. Evenly spaced peaks (for example 50, 100, 150 Hz) are a fundamental and its harmonics, usually a sign that the waveform isn't a pure sine.
- Find the noise floor, the uneven level between the peaks. A peak only means something if it stands clearly above it (see signal-to-noise ratio).
- Look at the shape of each peak. A wide skirt around a peak is usually leakage from the window, not real content (see windowing).
For a real signal (any measurement from a sensor or microphone), the FFT's output is symmetric: bins above mirror the ones below, as negative frequencies. So FFT plots show only bins 0 to (the one-sided spectrum), and double those amplitudes (except at 0 Hz and at the Nyquist frequency) so each tone's energy is counted once.
Amplitude, power or power spectral density?
An amplitude spectrum (as here) reads the size of each tone directly. A power spectrum shows the square of it. A power spectral density (PSD) divides power by the bin width, so random noise reads the same whatever the FFT size; vibration and noise measurements often use it.
FFT resolution: bins, bin width and FFT size
An FFT of samples taken at a sample rate gives bins at
where is the bin width (or frequency resolution) and is how long the block lasts. The resolution depends only on how long you record, not on how fast you sample. Sampling faster raises the Nyquist frequency; recording longer makes the bins narrower.
For audio sampled at 48,000 samples a second:
| FFT size | Bin width | Block length | Good for |
|---|---|---|---|
| 1,024 | 46.9 Hz | 21 ms | Fast-moving level meters and real-time displays |
| 4,096 | 11.7 Hz | 85 ms | General audio analysis |
| 16,384 | 2.9 Hz | 341 ms | Separating close musical notes or mains harmonics |
| 65,536 | 0.73 Hz | 1.4 s | Fine detail on steady signals, such as machine vibration |
The trade-off is between detail in frequency and detail in time. A long block gives narrow bins but blurs anything that changes within it. To follow a signal that changes, take many short FFTs one after another and draw them as a spectrogram.
How close can two tones be?
As a rule of thumb, two tones of similar size show as separate peaks when they are further apart than a peak's width 6 dB below its top: about 1.2 bins with no window and 2 bins with a Hann window (Harris, 1978). Windowing widens each peak, so it costs some resolution.
Windowing and spectral leakage
The FFT assumes the block repeats forever. If a tone completes a whole number of cycles in the block, the end joins the start smoothly and the tone lands in exactly one bin. If it doesn't, which is nearly always, the repeat has a jump at the join. That jump spreads the tone's energy into many other bins. This is spectral leakage.
Leakage does two kinds of harm:
- It hides weak tones. The skirts of a strong peak can be higher than a small peak nearby.
- It lowers the peak. A tone exactly halfway between two bins reads about 3.9 dB too low with no window. This is called scalloping loss.
A window function fixes most of this. Before the FFT, each sample is multiplied by a weight that is largest in the middle of the block and falls towards the ends, so the jump at the join disappears. It also widens the central peak (less frequency detail) and lowers the overall level, which the amplitude scaling corrects.
| Window | Formula, | Highest side lobe | Central peak width (to first zero) | Peak drop between bins | Best for |
|---|---|---|---|---|---|
| Rectangular (none) | -13 dB | ±1 bin | 3.9 dB | Tones that fit the block exactly; short transients that start and end inside it | |
| Hann (Hanning) | -31 dB | ±2 bins | 1.4 dB | A good default for most signals, noise and random vibration | |
| Hamming | -43 dB | ±2 bins | 1.8 dB | Lower close-in leakage than Hann, often used in speech processing | |
| Blackman | -58 dB | ±3 bins | 1.1 dB | Finding weak tones near strong ones |
We measured these figures with the FFT code on this page. They match the standard values in Harris (1978) to within rounding; see Sources. Far from the peak, leakage falls away quickly with Hann and Blackman but only slowly with Hamming, whose side lobes stay in the -40s and -50s of dB for many bins. For the most accurate peak heights, test equipment also offers a flat-top window, with almost no peak drop but a very wide peak.
In the live example, with the moving tone at 120.5 Hz, switch the window to Rectangular. Its skirt rises over the weak 160 Hz tone. Switch back to Hann or Blackman and the small peak reappears. Then move the tone to exactly 120.0 Hz: with a rectangular window the leakage vanishes, because the tone now fits the block.
Zero padding: a smoother plot, not more detail
Zero padding means adding zeros to the end of the block before the FFT, for example 1,024 samples plus 3,072 zeros for a 4,096-point FFT. The result has four times as many points, a quarter of a bin apart. That draws the same spectrum at more points, like interpolating between them, so peaks look smoother and their tops are easier to locate. It doesn't improve the resolution: the bin width still depends on the real data, , so two tones too close to separate in 1,024 samples stay merged however many zeros you add.
Padding is also used to reach the next power of 2 so a radix-2 FFT can run, and before fast convolution so the result doesn't wrap around. For how zero padding relates to leakage, see does zero padding reduce spectral leakage? in the window functions guide.
FFT vs DFT, Fourier transform and spectrogram
Use an FFT for the spectrum of a block of samples, and one of the related tools below when you need something else.
| If you need… | Use | Why |
|---|---|---|
| The spectrum of a block of samples | FFT | The standard tool: same result as the DFT, far less work |
| A handful of specific frequencies (for example, detecting phone keypad tones) | Direct DFT of those bins, or the Goertzel algorithm | Cheaper than a full FFT when you need only a few bins |
| The maths of a continuous signal, on paper | Fourier transform | The continuous version the DFT and FFT approximate |
| How the frequencies change over time | Spectrogram (short-time FFT) | Many FFTs of short, overlapping blocks, drawn as a heatmap |
| To filter or smooth a signal | A low-pass filter, or FFT-based convolution for long filters | Filtering changes the signal; an FFT only measures it |
What FFT analysis is used for
FFT analysis is used wherever a signal needs to be split into its frequencies, often many times a second.
- Audio: spectrum analysers, equalisers, pitch detection, room measurement and finding hum or noise.
- Vibration and machine monitoring: bearing and shaft faults show up as peaks linked to the machine's speed.
- Oscilloscopes and test equipment: most digital oscilloscopes have an FFT mode that shows the spectrum of the captured waveform.
- Communications, imaging and science: OFDM (Wi-Fi, 4G and 5G), MRI scanners, astronomy, seismology and spectroscopy all run on forward and inverse FFTs.
- Fast filtering: long filters and convolution run faster through an FFT than directly.
Common FFT mistakes
Most FFT mistakes come from the block, the window or the scaling, not the algorithm.
- No window on a signal that doesn't fit the block. Leakage then hides weak tones and lowers peak heights. Use Hann unless you have a reason not to.
- Forgetting to scale. Raw FFT magnitudes grow with . Divide by the sum of the window (and double the one-sided bins) to read amplitudes.
- Mixing up 10 and 20 log. Use for amplitude and for power, or every level is off by a factor of two in dB.
- Aliasing before the FFT. Frequencies above fold back into the spectrum as false peaks. Filter them out with an analogue or low-pass filter before sampling or downsampling.
- Leaving in the DC offset. A constant offset makes a large 0 Hz bin, and its leakage can swamp low frequencies. Subtract the mean first.
- Reading a single FFT of noise as fact. Noise in one FFT is ragged. Average the spectra of several blocks (Welch's method) for a steady estimate.
How to plot an FFT in JavaScript, React or Angular
Each time you change a control, this demo builds a new test signal sampled at 1,024 Hz, windows it, takes its FFT and redraws the spectrum. The example below runs the FFT in your browser with the plain JavaScript functions in the code. Move the tone, change the window, the FFT size , zero padding and the scale; the line under the controls says where the tone falls among the bins. Hover over the spectrum to read a bin, scroll to zoom into a frequency range, drag to pan and double-click to reset.
Here is the code for this example. The JavaScript tab includes the FFT, window and spectrum functions; the React and Angular tabs reuse them.
- JavaScript
- React
- Angular
// FFT spectrum analyser: a test signal and its FFT magnitude spectrum, in JavaScript with SciChart.js.
// The FFT and window 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 n = 8, index 1 = 001 swaps with 4 = 100)
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: sizes 2, 4, 8 ... n (log2(n) stages).
// Each "butterfly" turns a and b into a + w*b and a - w*b, where w is a twiddle factor e^(-2*pi*i*k/size).
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;
}
}
}
}
// Window functions (the periodic form used for spectrum analysis). They taper the ends of the block
// towards zero, so a tone that doesn't fit a whole number of cycles leaks less into other bins.
function makeWindow(type, n) {
const w = new Float64Array(n);
for (let i = 0; i < n; i++) {
const x = (2 * Math.PI * i) / n;
if (type === "hann") w[i] = 0.5 - 0.5 * Math.cos(x);
else if (type === "hamming") w[i] = 0.54 - 0.46 * Math.cos(x);
else if (type === "blackman") w[i] = 0.42 - 0.5 * Math.cos(x) + 0.08 * Math.cos(2 * x);
else w[i] = 1; // rectangular: no window
}
return w;
}
// One-sided amplitude spectrum: window the samples, zero pad, FFT, and scale so a sine of amplitude A
// centred on a bin reads A. Returns the frequency of each bin (0 to sampleRate / 2) and its amplitude.
function amplitudeSpectrum(samples, sampleRate, windowType, padFactor) {
const n = samples.length;
const size = n * padFactor; // zero padding: extra zeros after the samples
const window = makeWindow(windowType, n);
const re = new Float64Array(size);
const im = new Float64Array(size);
let windowSum = 0;
for (let i = 0; i < n; i++) {
re[i] = samples[i] * window[i];
windowSum += window[i];
}
fft(re, im);
const bins = size / 2 + 1; // bins above sampleRate / 2 mirror these, so drop them
const frequencies = new Float64Array(bins);
const amplitudes = new Float64Array(bins);
for (let k = 0; k < bins; k++) {
frequencies[k] = (k * sampleRate) / size;
const oneSided = k === 0 || k === size / 2 ? 1 : 2; // fold the negative frequencies in
amplitudes[k] = (oneSided * Math.hypot(re[k], im[k])) / windowSum;
}
return { frequencies, amplitudes };
}
// Test signal: three sine tones plus a little seeded random noise, so it looks the same every time.
// 50 Hz (amplitude 1), a tone you can move (amplitude 0.5) and a weak 160 Hz tone (0.003, about -50 dB).
function makeTestSignal(count, sampleRate, movingToneHz) {
let seed = 11;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
const time = new Float64Array(count);
const values = new Float64Array(count);
for (let i = 0; i < count; i++) {
const t = i / sampleRate;
const noise = (random() + random() + random() + random() + random() + random() - 3) * 0.007;
time[i] = t;
values[i] =
Math.sin(2 * Math.PI * 50 * t) +
0.5 * Math.sin(2 * Math.PI * movingToneHz * t) +
0.003 * Math.sin(2 * Math.PI * 160 * t) +
noise;
}
return { time, values };
}
async function createFftCharts(timeDiv, spectrumDiv) {
const {
SciChartSurface,
NumericAxis,
NumberRange,
NumericLabelProvider,
EAutoRange,
EXyDirection,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const SAMPLE_RATE = 1024; // samples per second, so the highest frequency shown (Nyquist) is 512 Hz
// Top chart: the samples going into the FFT, before and after the window
const timeChart = await SciChartSurface.create(timeDiv, { theme: new SciChartJsNavyTheme() });
const timeSurface = timeChart.sciChartSurface;
const timeXAxis = new NumericAxis(timeChart.wasmContext, { axisTitle: "Time (s)", labelPrecision: 2 });
timeSurface.xAxes.add(timeXAxis);
timeSurface.yAxes.add(
new NumericAxis(timeChart.wasmContext, { axisTitle: "Signal", visibleRange: new NumberRange(-2, 2), labelPrecision: 1 })
);
const rawSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Samples" });
const windowedSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "After the window" });
timeSurface.renderableSeries.add(
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: rawSeries, stroke: "#50C7E088" }),
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: windowedSeries, stroke: "#F48420" })
);
timeSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
// Bottom chart: the FFT magnitude spectrum, from 0 Hz to the Nyquist frequency
const spectrumChart = await SciChartSurface.create(spectrumDiv, { theme: new SciChartJsNavyTheme() });
const spectrumSurface = spectrumChart.sciChartSurface;
spectrumSurface.xAxes.add(
new NumericAxis(spectrumChart.wasmContext, {
axisTitle: "Frequency (Hz)",
visibleRange: new NumberRange(0, SAMPLE_RATE / 2),
labelPrecision: 0
})
);
const levelLabels = new NumericLabelProvider({ labelPrecision: 0 });
const levelAxis = new NumericAxis(spectrumChart.wasmContext, { autoRange: EAutoRange.Never, labelProvider: levelLabels });
let unit = "dB";
spectrumSurface.yAxes.add(levelAxis);
const spectrumSeries = new XyDataSeries(spectrumChart.wasmContext, { dataSeriesName: "Spectrum", dataIsSortedInX: true });
spectrumSurface.renderableSeries.add(
new FastLineRenderableSeries(spectrumChart.wasmContext, { dataSeries: spectrumSeries, stroke: "#50C7E0", strokeThickness: 2 })
);
// Hover to read a bin, scroll to zoom into a frequency range, drag to pan, double-click to reset
spectrumSurface.chartModifiers.add(
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (seriesInfos) =>
seriesInfos.map((info) => `${info.formattedXValue} Hz: ${info.formattedYValue} ${unit}`)
}),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
// Recompute everything from the settings: { toneHz, windowType, size, padFactor, decibels }
const update = (settings) => {
const { time, values } = makeTestSignal(settings.size, SAMPLE_RATE, settings.toneHz);
const window = makeWindow(settings.windowType, settings.size);
rawSeries.clear();
rawSeries.appendRange(time, values);
windowedSeries.clear();
windowedSeries.appendRange(time, values.map((v, i) => v * window[i]));
timeXAxis.visibleRange = new NumberRange(0, settings.size / SAMPLE_RATE);
const { frequencies, amplitudes } = amplitudeSpectrum(values, SAMPLE_RATE, settings.windowType, settings.padFactor);
// Decibels relative to an amplitude of 1: 20 * log10(amplitude). A floor avoids log10(0) = -Infinity
const levels = settings.decibels ? amplitudes.map((a) => 20 * Math.log10(Math.max(a, 1e-10))) : amplitudes;
spectrumSeries.clear();
spectrumSeries.appendRange(frequencies, levels);
unit = settings.decibels ? "dB" : "";
levelAxis.axisTitle = settings.decibels ? "Amplitude (dB)" : "Amplitude";
levelLabels.precision = settings.decibels ? 0 : 2;
levelAxis.visibleRange = settings.decibels ? new NumberRange(-100, 5) : new NumberRange(0, 1.1);
spectrumSeries.dataSeriesName = `Spectrum, bin width ${SAMPLE_RATE / settings.size} Hz`;
};
return { update, sampleRate: SAMPLE_RATE };
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} from "scichart";
// fft, makeWindow and amplitudeSpectrum: copy them from the JavaScript tab
import { amplitudeSpectrum } from "./fft";
const SAMPLE_RATE = 1024; // your sample rate, in samples per second
// 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)", visibleRange: new NumberRange(0, SAMPLE_RATE / 2) })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { axisTitle: "Amplitude (dB)", visibleRange: new NumberRange(-100, 5) })
);
// Your block of samples (a power of 2 long), windowed and transformed
const samples = getYourSamples();
const { frequencies, amplitudes } = amplitudeSpectrum(samples, SAMPLE_RATE, "hann", 1);
const levels = amplitudes.map((a) => 20 * Math.log10(Math.max(a, 1e-10)));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: frequencies, yValues: 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 FftSpectrum = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} from "scichart";
// fft, makeWindow and amplitudeSpectrum: copy them from the JavaScript tab
import { amplitudeSpectrum } from "./fft";
const SAMPLE_RATE = 1024; // your sample rate, in samples per second
@Component({
selector: "app-fft-spectrum",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class FftSpectrumComponent {
// 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)", visibleRange: new NumberRange(0, SAMPLE_RATE / 2) })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { axisTitle: "Amplitude (dB)", visibleRange: new NumberRange(-100, 5) })
);
// Your block of samples (a power of 2 long), windowed and transformed
const samples = getYourSamples();
const { frequencies, amplitudes } = amplitudeSpectrum(samples, SAMPLE_RATE, "hann", 1);
const levels = amplitudes.map((a) => 20 * Math.log10(Math.max(a, 1e-10)));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: frequencies, yValues: 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:
- The spectrum is an
XyDataSeriesof frequencies and levels, drawn by aFastLineRenderableSeries. SetdataIsSortedInX: true, since FFT bins are already in order. - To update it live, keep the data series and call
clear()thenappendRange()with each new spectrum, as the example'supdate()function does. SciChart.js redraws on the next frame. - A fixed y-axis range (
autoRange: EAutoRange.Neverand avisibleRangein dB) stops the axis jumping as the noise changes. - The FFT itself is plain JavaScript. Swap in any FFT library you prefer; the chart code stays the same.
See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart. It runs the FFT on your microphone input and draws the waveform, the spectrum and a spectrogram.
Go deeper: SciChart.js line series documentation, and the spectrogram guide for drawing many FFTs over time.
Frequently asked questions
What does FFT stand for?
FFT stands for fast Fourier transform. It is a fast way to compute the discrete Fourier transform (DFT) of a block of samples, which tells you how much of each frequency the block contains. FFT analysis means using it to look at a signal's spectrum.
What is the difference between the DFT and the FFT?
The DFT is the calculation: it turns N samples into N frequency bins. The FFT is a family of algorithms that compute exactly the same result much faster. Computed directly, the DFT takes about N squared operations; an FFT takes about N log2 N, which for 1,024 samples is about 100 times fewer.
What is FFT size, and how do I choose it?
FFT size is the number of samples N in each block. It sets the bin width, which is the sample rate divided by N. A bigger N gives finer frequency detail but needs a longer recording (N divided by the sample rate) and reacts more slowly to change. Choose N so the bin width is no more than about half the gap between the closest frequencies you need to separate.
Why does my FFT show a mirror image or two peaks for one tone?
For a real signal, the FFT's second half mirrors the first: bins above N/2 are the negative frequencies. Plot only bins 0 to N/2, which run from 0 Hz to the Nyquist frequency, and double their amplitude (except the first and last) to get the one-sided spectrum.
Does a JavaScript FFT give the same result as NumPy or MATLAB?
Yes, if the conventions match. A standard JavaScript FFT, numpy.fft.fft and MATLAB fft(x) all compute the same unnormalised DFT with the same sign, so bin is identical to within rounding when you use 64-bit numbers (Float64Array). numpy.fft.rfft returns only bins 0 to , the same half you plot; in MATLAB, compute X = fft(x); and keep X(1:N/2+1), since MATLAB counts from 1.
When the numbers don't match, the window is the usual cause. numpy.hanning(N) and MATLAB hann(N) are symmetric, while hann(N, 'periodic') and scipy.signal.get_window('hann', N) are periodic (the demo above uses the periodic form), so use the same one on both sides. Scale amplitudes the same way too: divided by the window's sum, except at bin 0 and bin .
How do I plot an FFT in JavaScript?
Window the samples, run an FFT (a short radix-2 function is enough), keep bins 0 to N/2, and convert each magnitude to an amplitude or decibels. With SciChart.js, put the frequencies and levels in an XyDataSeries and draw them with a FastLineRenderableSeries; call clear() and appendRange() each time new samples arrive. For React or Angular, wrap that chart setup in scichart-react or scichart-angular.
Sources
- Cooley, J. W. and Tukey, J. W. (1965), An Algorithm for the Machine Calculation of Complex Fourier Series. Mathematics of Computation, 19(90), 297–301. The radix-2 FFT.
- Heideman, M. T., Johnson, D. H. and Burrus, C. S. (1984), Gauss and the History of the Fast Fourier Transform. IEEE ASSP Magazine, 1(4), 14–21. Gauss's earlier use of the idea.
- 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. Window side lobes, scalloping loss and bandwidth.
- Smith, S. W., The Scientist and Engineer's Guide to Digital Signal Processing: chapter 8, The Discrete Fourier Transform, chapter 9, Applications of the DFT (windows, resolution and zero padding) and chapter 12, The Fast Fourier Transform.
- Smith, J. O., Spectral Audio Signal Processing, Center for Computer Research in Music and Acoustics (CCRMA), Stanford University. Windows, zero padding and spectrum analysis in depth.
- Burnett-Thompson, A. (2007), A 3D Local Positioning System to track A Neutrally Buoyant Flow Follower, PhD thesis, University of Manchester, UK, chapter 3. The associated published paper is Burnett-Thompson, A. and York, T. (2007), A 3D Acoustic Local Positioning System to Track a Neutrally Buoyant Flow Follower, IEEE Instrumentation and Measurement Technology Conference (IMTC 2007). The bit-reversal, butterfly and 8-point flow-graph diagrams on this page are adapted from it.