Tone.js Tone.Sampler loaded callback guide

When working with sampler instruments in web audio projects, ensuring all audio files are fully loaded before playback is crucial for a seamless user experience. This article explains the callback options provided by Tone.Sampler in Tone.js—specifically onload and onerror—to verify when your samples are successfully loaded and ready to play, along with code examples demonstrating their implementation.


The onload Callback

The primary callback option offered by Tone.Sampler to verify that all samples have successfully loaded is the onload event handler. This callback triggers automatically once every audio buffer specified in your configuration has been fetched and decoded.

You can define onload in two ways: inside the options object passed to the constructor, or as a positional argument.

Passing an options object to the Tone.Sampler constructor is the cleanest way to define your callbacks.

const sampler = new Tone.Sampler({
  urls: {
    C4: "C4.mp3",
    E4: "E4.mp3",
    G4: "G4.mp3"
  },
  baseUrl: "https://tonejs.github.io/audio/drum-samples/",
  onload: () => {
    console.log("All samples have loaded successfully!");
    // Enable your play button or start your audio sequence here
  }
}).toDestination();

Method 2: Using Positional Arguments

Alternatively, you can pass the onload function as the second argument in the constructor.

const sampler = new Tone.Sampler(
  {
    C4: "C4.mp3",
    E4: "E4.mp3"
  },
  () => {
    console.log("Samples loaded via positional callback!");
  },
  "https://tonejs.github.io/audio/drum-samples/"
).toDestination();

The onerror Callback

To ensure robust error handling, Tone.Sampler also provides an onerror callback. This function executes if one or more sample files fail to load (e.g., due to a 404 network error or an unsupported file format).

const sampler = new Tone.Sampler({
  urls: {
    C4: "C4-missing-file.mp3"
  },
  baseUrl: "https://tonejs.github.io/audio/drum-samples/",
  onload: () => {
    console.log("Loaded successfully.");
  },
  onerror: (error) => {
    console.error("Failed to load sampler audio files:", error);
  }
}).toDestination();

Global Alternative: Tone.loaded()

If you are dealing with multiple samplers or other audio buffers simultaneously, you can use the global Tone.loaded() method. This returns a Promise that resolves when all currently loading buffers in your Tone.js context are successfully resolved.

const sampler = new Tone.Sampler({
  urls: {
    C4: "C4.mp3"
  },
  baseUrl: "https://tonejs.github.io/audio/drum-samples/"
}).toDestination();

// Wait for all Tone.js buffers to load
Tone.loaded().then(() => {
  console.log("Global buffers loaded. Ready for playback!");
});