Set Tone.Player Loop Start and End in Tone.js
In Tone.js, looping specific sections of an audio buffer is a
fundamental technique for creating dynamic web audio applications. This
guide provides a straightforward explanation of how to configure the
Tone.Player object to loop a specific portion of an audio
sample by setting its loop, loopStart, and
loopEnd properties.
Enabling and Configuring the Loop
To loop a specific section of an audio file using
Tone.Player, you need to configure three key
properties:
loop: Set this boolean totrueto enable looping.loopStart: Define the start time of the loop in seconds (or using Tone.js Time notation).loopEnd: Define the end time of the loop in seconds.
Code Example: Initialization
You can define these properties directly in the constructor options
when creating the Tone.Player instance:
// Create and configure the player
const player = new Tone.Player({
url: "https://tonejs.github.io/audio/berlin/synth.mp3",
loop: true,
loopStart: 0.5, // Start loop at 0.5 seconds
loopEnd: 2.5, // End loop at 2.5 seconds
onload: () => {
// Start playback once the audio file is loaded
player.start();
}
}).toDestination();Code Example: Dynamic Updates
You can also set or change the loop points dynamically at any time after the player has been created:
const player = new Tone.Player("https://tonejs.github.io/audio/berlin/synth.mp3").toDestination();
// Enable looping
player.loop = true;
// Set loop points dynamically (in seconds)
player.loopStart = 1.0;
player.loopEnd = 3.0;
// Play the audio
Tone.loaded().then(() => {
player.start();
});Key Considerations
- Buffer Bounds: Ensure your
loopEndvalue does not exceed the total duration of the audio buffer, and thatloopStartis less thanloopEnd. - Time Notation: While seconds are the most common
unit,
loopStartandloopEndalso accept Tone.js Time notation (such as"4n"for a quarter note or"1m"for one measure) if the Transport is running and synchronized.