Load Multiple Audio Files into Tone.js Sampler
This article explains how to load multiple audio files into a
Tone.Sampler in Tone.js. You will learn how to map multiple
audio samples to specific musical notes, configure the sampler with a
base URL, and trigger the sounds once they are fully loaded into the
browser.
The Tone.Sampler Object
In Tone.js, Tone.Sampler is the best tool for creating
multi-sampled instruments. Instead of loading a single audio file, you
pass an object containing multiple note-to-audio-file mappings. Tone.js
automatically repitches the samples to fill in the gaps for notes you
didn’t explicitly define.
Step 1: Define the Sample Mapping
To load multiple files, create an object where the keys represent musical pitches (e.g., “C4”, “A4”) and the values are the paths to the corresponding audio files.
const sampleMap = {
"C4": "c4.mp3",
"E4": "e4.mp3",
"G4": "g4.mp3",
"C5": "c5.mp3"
};Step 2: Initialize the Sampler
Pass the mapping object into the Tone.Sampler
constructor. You can use the urls property for your
mapping, and optionally define a baseUrl to avoid repeating
the folder path for every file.
To ensure the audio is ready before you attempt to play it, use the
onload callback.
const sampler = new Tone.Sampler({
urls: {
C4: "c4.mp3",
E4: "e4.mp3",
G4: "g4.mp3",
C5: "c5.mp3",
},
baseUrl: "https://example.com/audio/samples/",
onload: () => {
console.log("All samples loaded successfully!");
}
}).toDestination();Step 3: Trigger the Samples
Once loaded, you can play any note. Tone.js will pitch-shift the nearest available sample to match the requested note.
To play a note, start the audio context (required by browsers) and
call triggerAttackRelease:
// Trigger a single note
sampler.triggerAttackRelease("D4", "8n");
// Trigger a chord using the loaded samples
sampler.triggerAttackRelease(["C4", "E4", "G4"], "2n");