How to Set Tempo in Tone.js
Controlling the speed of your playback is fundamental to web audio development. This article provides a quick guide on how to set and manipulate the tempo (Beats Per Minute, or BPM) of a project in Tone.js, covering both static initialization and dynamic, time-based adjustments during playback.
The Tone.Transport Object
In Tone.js, the tempo is managed globally by the
Tone.Transport object. The Transport represents the
timeline of your project, governing the playback, timing, and
synchronization of scheduled audio events.
Setting a Static Tempo
To set a basic, static tempo for your project, you modify the
value property of Tone.Transport.bpm. The
default tempo in Tone.js is 120 BPM.
// Set the tempo to 140 Beats Per Minute
Tone.Transport.bpm.value = 140;
// Start the transport to play scheduled events at the new tempo
Tone.Transport.start();You can set this value at any point before or after starting the Transport.
Changing Tempo Dynamically
Because Tone.Transport.bpm is a Tone.Signal
object, you do not have to settle for instant, abrupt tempo changes. You
can schedule smooth tempo transitions over time, which is useful for
creating accelerandos (speeding up) or ritardandos (slowing down).
1. Instant Change at a Specific Time
To schedule an instant tempo change at a precise point in the future,
use setValueAtTime:
// Change the tempo to 100 BPM exactly 2 seconds from the current time
Tone.Transport.bpm.setValueAtTime(100, "+2");2. Smooth Ramp Over Time
To smoothly transition from the current tempo to a target tempo, use
rampTo:
// Smoothly ramp the tempo to 160 BPM over the course of 4 seconds
Tone.Transport.bpm.rampTo(160, 4);By leveraging these properties, you can easily control the timing and pacing of any interactive audio project in Tone.js.