Real-Time Spectrum Analysis
Learn how to build a real-time audio spectrum analyzer.
Overview
The library provides a SpectrumAnalyzer utility that wraps the FFT engine with windowing and dB conversion for audio analysis.
Basic Usage
ts
import { createSpectrumAnalyzer } from 'webgpu-fft';
const sampleRate = 44100;
const analyzer = createSpectrumAnalyzer({
fftSize: 2048,
windowType: 'hann',
sampleRate,
});
// Analyze audio buffer (Float32Array from Web Audio API)
const audioBuffer = new Float32Array(2048);
// ... fill with audio samples ...
const spectrum = await analyzer.analyze(audioBuffer);
// spectrum contains dB values ready for visualization1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Visualization
ts
function drawSpectrum(canvas: HTMLCanvasElement, spectrum: Float32Array) {
const ctx = canvas.getContext('2d')!;
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = '#4f46e5';
const barWidth = width / spectrum.length;
for (let i = 0; i < spectrum.length; i++) {
const barHeight = ((spectrum[i] + 100) / 100) * height;
ctx.fillRect(i * barWidth, height - barHeight, barWidth - 1, barHeight);
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Frequency Bins
ts
const frequencies = analyzer.getFrequencies();
const frequencyResolution = frequencies[1] - frequencies[0];
console.log(`Each bin represents ${frequencyResolution} Hz`);
// Get frequency for a specific bin
function binToFrequency(binIndex: number): number {
return binIndex * frequencyResolution;
}
// Get bin index for a specific frequency
function frequencyToBin(frequency: number): number {
return Math.round(frequency / frequencyResolution);
}1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Next Steps
- Image Filtering - Apply filters in frequency domain
- Introduction - Back to tutorials overview