How to Loop an Audio Sprite in Howler.js

This article explains how to loop a specific audio sprite using the Howler.js library. You will learn how to configure looping directly within the sprite definition and how to dynamically enable looping during playback using JavaScript.

Method 1: Define the Loop in the Sprite Configuration

The easiest way to loop a specific audio sprite is by setting the loop parameter directly in the sprite definition. In Howler.js, the sprite property accepts an array of values in the format [offset, duration, loop].

To make a sprite loop, set the third parameter to true.

// Import or reference Howler.js
const sound = new Howl({
  src: ['sounds.mp3'],
  sprite: {
    laser: [0, 1000],          // Plays once (offset: 0ms, duration: 1000ms)
    backgroundBeat: [2000, 4000, true] // Loops (offset: 2000ms, duration: 4000ms, loop: true)
  }
});

// Play the looping sprite
sound.play('backgroundBeat');

In this example, calling sound.play('backgroundBeat') will continuously loop that specific 4-second segment of the audio file.

Method 2: Enable Looping Dynamically

If you want to control the looping behavior programmatically after the sprite has started playing, you can use the .loop() method. This requires capture of the unique sound ID returned by the .play() method.

const sound = new Howl({
  src: ['sounds.mp3'],
  sprite: {
    ambient: [1000, 5000] // Defined without a loop by default
  }
});

// Play the sprite and capture its unique instance ID
const soundId = sound.play('ambient');

// Dynamically set this specific instance to loop
sound.loop(true, soundId);

To stop the sprite from looping later, you can pass false to the loop method using the same ID:

// Stop the sprite from looping
sound.loop(false, soundId);