How to Loop a Sample in Tone.js Tone.Player
Looping audio samples is a fundamental technique in web audio
development. This article provides a quick and direct guide on how to
loop an audio sample loaded inside a Tone.Player in
Tone.js, covering the essential properties needed to enable looping, set
specific start and end points, and control playback.
To loop a sample in Tone.js, you need to set the loop
property of your Tone.Player instance to true.
By default, this property is set to false.
Step-by-Step Code Example
Here is the most direct way to load a sample, enable looping, and play it:
// 1. Create the player and load your audio file
const player = new Tone.Player({
url: "https://tonejs.github.io/audio/berlin/feudal.mp3",
onload: () => {
// 2. Enable looping
player.loop = true;
// 3. Start playback once the file is loaded
player.start();
}
}).toDestination();Setting Specific Loop Points
If you do not want to loop the entire audio file, you can define
specific start and end points for your loop using the
loopStart and loopEnd properties. These values
are defined in seconds (or Tone.js time values).
// Enable looping
player.loop = true;
// Set the loop to start at 1.5 seconds into the sample
player.loopStart = 1.5;
// Set the loop to end at 4.0 seconds into the sample
player.loopEnd = 4.0;
player.start();Key Properties Reference
player.loop: A boolean value (trueorfalse). Set this totrueto make the sample repeat indefinitely.player.loopStart: Defines the timestamp (in seconds or time notation) where the loop interval begins.player.loopEnd: Defines the timestamp (in seconds or time notation) where the loop interval ends and wraps back toloopStart.