Convert Tone.js Time Notation to Seconds
In web audio development, syncing visual events with audio cues often requires converting musical time notation, like quarter notes (“4n”), into seconds. This article explains how to use Tone.js, a popular Web Audio framework, to easily convert musical duration values into absolute time in seconds using its built-in Time utility.
In Tone.js, musical notation is dependent on the transport’s tempo
(BPM). To convert a notation like "4n" (a quarter note) or
"8n" (an eighth note) into seconds, you use the
Tone.Time() constructor combined with the
.toSeconds() method.
Here is the most straightforward way to perform the conversion:
import * as Tone from 'tone';
// Set the Transport BPM (beats per minute)
Tone.getTransport().bpm.value = 120;
// Convert a quarter note ("4n") to seconds
const quarterNoteInSeconds = Tone.Time("4n").toSeconds();
console.log(quarterNoteInSeconds); // Outputs: 0.5How It Works
- The Transport Tempo: Because musical time is
relative, the resulting seconds depend entirely on the current BPM of
Tone.getTransport(). At 120 BPM, one beat (a quarter note, or"4n") lasts exactly 0.5 seconds. If you increase the BPM to 240, the same code will return0.25seconds. - The
Tone.Time()Wrapper: This class can parse various timing strings. Beyond"4n", you can pass measures ("1m"), triplets ("4nt"), dotted notes ("4n."), or even mathematical expressions (like"4n + 8n"). - The
.toSeconds()Method: This method evaluates the parsed musical time against the current transport state and returns a floating-point number representing the duration in seconds.
Alternative Notation Examples
You can convert several other common musical notations using the exact same method:
// Eighth note
const eighthNote = Tone.Time("8n").toSeconds(); // 0.25 seconds at 120 BPM
// Two measures
const twoMeasures = Tone.Time("2m").toSeconds(); // 4.0 seconds at 120 BPM
// Combined notation (Quarter note + Eighth note)
const combined = Tone.Time("4n + 8n").toSeconds(); // 0.75 seconds at 120 BPM