How to Play a Random Sound with Howler.js
In this article, you will learn how to use the Howler.js library to select and play a random audio file from a predefined list. This guide covers how to set up your array of audio sources, generate a random selection using JavaScript, and trigger the playback using the Howler.js API.
1. Define Your Sound List
To start, create an array of strings containing the file paths to your audio files. This list can contain as many audio tracks as you need.
const soundFiles = [
'audio/bell.mp3',
'audio/chime.mp3',
'audio/click.mp3',
'audio/whistle.mp3'
];2. Create the Playback Function
To play a random sound, you need a function that selects a random index from your array, instantiates a new Howler instance, and plays the file.
function playRandomSound() {
// Get a random index from the array
const randomIndex = Math.floor(Math.random() * soundFiles.length);
const chosenSound = soundFiles[randomIndex];
// Initialize the Howl object with the selected source
const sound = new Howl({
src: [chosenSound],
html5: true // Use HTML5 Audio to handle larger files or ease loading
});
// Play the audio
sound.play();
}3. Trigger the Sound
You can trigger the playRandomSound function based on
user interaction, such as clicking a button on your web page.
<button onclick="playRandomSound()">Play Random Sound</button>Optimizing Performance (Optional)
If you are playing short sound effects frequently, creating a new
Howl instance every time can cause a slight delay. To
optimize performance, you can pre-load all sounds into an array of Howl
instances beforehand, and then play a random instance from that
array:
// Pre-load all sounds
const soundObjects = soundFiles.map(file => new Howl({ src: [file] }));
function playPreloadedRandomSound() {
const randomIndex = Math.floor(Math.random() * soundObjects.length);
soundObjects[randomIndex].play();
}