Limit Tone.PolySynth Max Polyphony in Tone.js
This article provides a straightforward guide on how to restrict the
maximum number of simultaneous voices in a Tone.PolySynth
within Tone.js. By setting the maxPolyphony option during
initialization, you can optimize your web application’s CPU performance
and prevent audio clipping caused by too many overlapping synthesizer
voices.
Using the maxPolyphony Option
In Tone.js, a Tone.PolySynth manages a pool of
single-voice synths (like Tone.Synth or
Tone.FMSynth). By default, the maximum polyphony is set to
32 voices. You can limit this number by passing a configuration object
as the second argument to the Tone.PolySynth constructor
and defining the maxPolyphony property.
Here is how to restrict a Tone.PolySynth to a maximum of
4 active voices:
import * as Tone from 'tone';
// Create a PolySynth limited to 4 simultaneous voices
const synth = new Tone.PolySynth(Tone.Synth, {
maxPolyphony: 4
}).toDestination();
// Play a chord
synth.triggerAttackRelease(["C4", "E4", "G4", "B4"], "4n");Configuring Voice-Specific Options
If you need to customize the settings of the underlying synthesizer
voice while limiting polyphony, pass those parameters inside the
options property of the configuration object.
const customizedSynth = new Tone.PolySynth(Tone.Synth, {
maxPolyphony: 3, // Limit to 3 voices
options: {
oscillator: {
type: "fatsawtooth"
},
envelope: {
attack: 0.1,
decay: 0.2,
sustain: 0.5,
release: 0.8
}
}
}).toDestination();Why Limit Polyphony?
- Performance Optimization: Each active voice in a synthesizer requires CPU cycles to calculate audio nodes. Restricting polyphony is essential for maintaining smooth performance on mobile devices and lower-end computers.
- Preventing Audio Clipping: When multiple audio signals are summed together, their amplitudes combine. Playing too many notes simultaneously can exceed the digital audio ceiling (0 dBFS), causing harsh digital distortion and clipping.
- Voice Stealing: When the
maxPolyphonylimit is reached and a new note is triggered, Tone.js automatically handles “voice stealing” by releasing the oldest active voice to free up resources for the incoming note.