How to Check if Tone Buffer Has Loaded in Tone.js

This article explains how to determine when an audio file has finished loading into a Tone.Buffer in Tone.js. You will learn how to use the instantiation callback, inspect the boolean state property, and leverage global promises to manage single or multiple audio assets efficiently.

1. Using the onload Callback

The most common and reliable way to detect when a buffer has finished loading is by passing a callback function as the second argument of the Tone.Buffer constructor. This function executes automatically as soon as the audio file is fully loaded and decoded.

const buffer = new Tone.Buffer("path/to/audio.mp3", () => {
    console.log("The audio file has finished loading!");
    // Trigger playback or update the UI here
});

You can also handle loading errors by providing an optional callback as the third argument:

const buffer = new Tone.Buffer(
    "path/to/audio.mp3",
    () => console.log("Loaded successfully!"),
    (error) => console.error("Loading failed:", error)
);

2. Checking the loaded Property

If you need to verify the status of a buffer synchronously at a specific moment in your application’s lifecycle, you can query the instance’s read-only .loaded property. This property returns a boolean value.

const buffer = new Tone.Buffer("path/to/audio.mp3");

// Checking the status later in your code
if (buffer.loaded) {
    console.log("The buffer is ready for playback.");
} else {
    console.log("The buffer is still loading.");
}

3. Resolving with Tone.loaded()

When managing multiple Tone.Buffer or Tone.Player instances, checking them individually can become cumbersome. Tone.js provides a global utility called Tone.loaded() which returns a promise that resolves only when all currently loading buffers in your application have completed loading.

const kick = new Tone.Buffer("kick.wav");
const snare = new Tone.Buffer("snare.wav");
const hihat = new Tone.Buffer("hihat.wav");

Tone.loaded().then(() => {
    console.log("All audio assets are loaded and ready to play.");
});