Play Specific Audio Sprite in Howler.js

This guide provides a straightforward explanation of how to play a specific audio sprite section using Howler.js. You will learn how to define sprite intervals in your configuration and trigger them using their designated keys, allowing you to manage multiple sound effects within a single audio file efficiently.

An audio sprite is a single audio file that contains multiple individual sounds. Using sprites reduces HTTP requests and improves performance in web applications. To play a specific section of this file, you must define the sprite property when instantiating the Howl object.

1. Define the Sprite in the Howl Instance

When creating a new Howl instance, pass a sprite object in the configuration. Each key in this object represents the name of your sprite, and the value is an array containing the start time (offset) and the duration of the audio section, both measured in milliseconds.

const sound = new Howl({
  src: ['sounds.mp3', 'sounds.ogg'],
  sprite: {
    blast: [0, 1000],      // Starts at 0ms, lasts 1000ms
    laser: [2000, 500],     // Starts at 2000ms, lasts 500ms
    winner: [3000, 2000]    // Starts at 3000ms, lasts 2000ms
  }
});

2. Play the Specific Sprite Section

To play a defined section, pass the string key of the sprite as the argument to the play() method.

// Plays the laser sound effect
sound.play('laser');

// Plays the blast sound effect
sound.play('blast');

3. Loop a Specific Sprite (Optional)

If you want a specific sprite section to loop continuously, you can add a third boolean parameter true inside the sprite’s definition array.

const sound = new Howl({
  src: ['sounds.mp3'],
  sprite: {
    ambientBeat: [5000, 10000, true] // Loops the 10-second segment starting at 5000ms
  }
});

// Play the looping ambient beat
sound.play('ambientBeat');