How to Loop Audio in Howler.js

This article provides a quick guide on how to continuously loop an audio track using the Howler.js JavaScript library. You will learn how to enable looping both during the initialization of your audio player and dynamically during active playback using clear, practical code examples.

Method 1: Looping Audio on Initialization

The most straightforward way to loop an audio track in Howler.js is to define the loop property when instantiating the Howl object. Setting this property to true ensures that the audio track automatically starts over once it reaches the end.

// Import or ensure Howler is loaded in your project
const sound = new Howl({
  src: ['track.mp3'],
  loop: true,
  html5: true // Recommended for longer audio tracks
});

// Play the looping audio
sound.play();

Method 2: Enabling Looping Dynamically

If you want to toggle the loop state of an audio track while it is already playing, you can use the .loop() method. Passing true or false into this method will change the behavior of the current playback on the fly.

const sound = new Howl({
  src: ['track.mp3']
});

// Start playing without a loop
sound.play();

// Enable looping dynamically after playback has started
sound.loop(true);

// Disable looping dynamically later on
sound.loop(false);

Looping Specific Audio Instances

If you are playing multiple instances of the same sound file and only want to loop a specific instance, you can pass the unique sound ID returned by the .play() method into the .loop() function.

const sound = new Howl({
  src: ['effect.mp3']
});

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

// Apply the loop specifically to this playing instance
sound.loop(true, soundId);