How to Define Audio Sprites in Howler.js
This article provides a straightforward guide on how to define and
use audio sprites within a Howler.js setup. You will learn how to
configure the Howl library, format the sprite
property using millisecond-based timing, and trigger specific segments
of a single audio file in your web applications.
Defining the Sprite Property
To define an audio sprite in Howler.js, you pass a
sprite object to the Howl constructor. An
audio sprite is a single audio file containing multiple sounds. By
defining sprites, you tell Howler.js the exact start time and duration
of each individual sound within that file.
The sprite object uses key-value pairs where the key is
the name of your sprite, and the value is an array defining its
timing:
spriteName: [offset, duration, loop]- offset: The starting point of the sound in milliseconds.
- duration: The length of the sound in milliseconds.
- loop (optional): A boolean
(
trueorfalse) indicating if this specific sprite should loop when played.
Step-by-Step Implementation
Here is a complete code example showing how to initialize a
Howl instance with defined sprites:
// Initialize the Howl object with audio sprites
const soundEffects = new Howl({
src: ['sounds.mp3', 'sounds.ogg'],
sprite: {
laser: [0, 1000], // Starts at 0ms, lasts 1 second
explosion: [1500, 2000], // Starts at 1.5s, lasts 2 seconds
winner: [4000, 3000, true] // Starts at 4s, lasts 3 seconds, and loops
}
});Playing a Defined Sprite
Once your sprites are defined, you can play them individually by
passing the sprite’s key name as a string to the .play()
method:
// Play the laser sound
soundEffects.play('laser');
// Play the looping winner sound
soundEffects.play('winner');By referencing the specific sprite name, Howler.js automatically handles seeking to the correct timestamp, playing for the defined duration, and stopping or looping the audio as specified.