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:

  1. loop: Set this boolean to true to enable looping.
  2. loopStart: Define the start time of the loop in seconds (or using Tone.js Time notation).
  3. 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