How to Play Audio from a Specific Time in Howler.js

This article explains how to play audio from a specific timestamp using the Howler.js JavaScript library. You will learn the two most effective methods to achieve this: using the seek() method for dynamic playback control, and using audio sprites for predefined segments.

Method 1: Using the seek() Method

The most common way to play a sound from a specific timestamp is by using the seek() method. This method defines the playback position in seconds.

To ensure the audio is fully loaded before attempting to change its position, you should wrap your play and seek actions inside the onload event or a user-triggered event like a button click.

// Initialize the sound
const sound = new Howl({
  src: ['audio.mp3'],
  html5: true // Recommended for larger audio files
});

// Play the sound and seek to 15 seconds once loaded
sound.once('load', function() {
  const soundId = sound.play();
  sound.seek(15, soundId); // Seek to 15 seconds
});

If the sound is already playing and you want to jump to a specific time, you can call the seek() method directly:

// Jump to 45 seconds during active playback
sound.seek(45);

Method 2: Using Audio Sprites

If you have specific segments of an audio file that you want to play repeatedly from a set timestamp, audio sprites are the ideal choice. Sprites allow you to define a start time and a duration (both in milliseconds).

const sound = new Howl({
  src: ['audio.mp3'],
  sprite: {
    chorus: [30000, 15000] // Starts at 30 seconds (30000ms) and plays for 15 seconds
  }
});

// Play the predefined segment
sound.play('chorus');

By utilizing either the dynamic seek() method or predefined audio sprites, you can easily control the starting playback position of any audio file in Howler.js.