Configure FFT Analysis with Tone.Analyser in Tone.js
This article provides a quick guide on how to configure and execute a
Fast Fourier Transform (FFT) analysis using Tone.Analyser
in the Tone.js framework. You will learn how to initialize the analyzer,
set the correct parameters such as FFT size, connect audio sources, and
retrieve frequency data for visualizers or audio analysis in your web
applications.
1. Initialize the Analyser
To perform an FFT analysis, you must instantiate
Tone.Analyser and pass "fft" as the first
argument. You can also specify the FFT size as the second argument.
// Initialize an FFT analyzer with a bin size of 1024
const analyser = new Tone.Analyser("fft", 1024);2. Configure Key Parameters
The Tone.Analyser class accepts a configuration object
or individual arguments to customize the behavior of the FFT:
- Type (
type): Must be set to"fft"to analyze frequency domain data (as opposed to"waveform"for time-domain data). - Size (
size): This represents the FFT size, which determines the number of frequency bins. It must be a power of two between 32 and 32768 (e.g., 256, 512, 1024, 2048). The resulting data array length will be half of this size (size / 2). - Smoothing (
smoothing): A value between 0 and 1 that represents the averaging constant from the last analysis frame. A higher value smooths out the transitions between analysis frames.
You can adjust these properties dynamically after initialization:
analyser.size = 2048; // Increase frequency resolution
analyser.smoothing = 0.8; // Smooth out the frequency spikes3. Connect the Audio Source
To analyze audio, you must route your Tone.js source (such as a Synth, Player, or Sampler) through the analyzer.
const synth = new Tone.Synth().connect(analyser);
// Connect the analyser to the main output (destination) to hear the audio
analyser.toDestination();4. Retrieve and Process the Frequency Data
To get the actual analysis data, call the getValue()
method inside an animation loop (such as
requestAnimationFrame). This method returns a
Float32Array containing decibel values ranging from
-Infinity to 0.
function analyzeAudio() {
requestAnimationFrame(analyzeAudio);
// Retrieve the FFT data array
const data = analyser.getValue();
// 'data' is a Float32Array of length (analyser.size / 2)
// For size 1024, data.length will be 512
console.log(data);
}
// Start the loop after user interaction and audio playback begins
Tone.start();
synth.triggerAttackRelease("C4", "8n");
analyzeAudio();