Implementing Compression with Tone.js Compressor

This article provides a practical guide on how to implement and configure a compression effect using Tone.Compressor in Tone.js. You will learn how to initialize the compressor, customize its key parameters—such as threshold, ratio, attack, and release—and connect it to your audio source to control the dynamic range of your web audio applications.

What is Tone.Compressor?

Tone.Compressor is a built-in node in Tone.js that reduces the dynamic range of an audio signal. It lowers the volume of loud signals that exceed a certain threshold, helping to prevent clipping, smooth out volume spikes, and create a more cohesive and polished mix.

Step-by-Step Implementation

To use the compressor, you need to import Tone.js, instantiate the Tone.Compressor object, configure its parameters, and route your audio source through it.

1. Initialize the Compressor

You can create a compressor with default settings or pass an options object to define its initial behavior.

// Create a compressor with custom settings
const compressor = new Tone.Compressor({
  threshold: -24, // in decibels
  ratio: 4,       // reduction ratio
  knee: 30,       // smoothness of the transition
  attack: 0.03,   // in seconds
  release: 0.25   // in seconds
}).toDestination();

2. Understanding the Parameters

3. Connect an Audio Source

To apply the effect, connect your audio source (like a synthesizer, player, or oscillator) directly to the compressor instead of the default destination.

// Create a synthesizer
const synth = new Tone.Synth().connect(compressor);

// Trigger a note to hear the compressed sound
Tone.loaded().then(() => {
  synth.triggerAttackRelease("C4", "8n");
});

4. Modifying Parameters Dynamically

You can adjust the compressor’s parameters in real-time during playback by accessing its properties. Because these properties are Tone.js AudioParams, you must modify their value property.

// Change threshold and ratio on the fly
compressor.threshold.value = -12;
compressor.ratio.value = 8;