Seek to a Specific Position in Howler.js

This article explains how to change and retrieve the playback position of an audio file using the Howler.js library. You will learn how to use the seek() method to jump to a specific time in seconds, handle seeking for specific audio instances, and ensure the audio is fully loaded before performing a seek operation.

Using the seek() Method

In Howler.js, the seek() method is used to both find the current playback position and jump to a specific time. The time is always defined in seconds.

1. Jumping to a Specific Time

To move the playback to a specific timestamp, pass the target time in seconds as the first parameter to the seek() method.

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

// Play the audio
sound.play();

// Seek to 30 seconds into the audio file
sound.seek(30);

2. Getting the Current Playback Position

If you call the seek() method without any parameters, it returns the current playback position in seconds.

// Get the current time of the audio
const currentTime = sound.seek();
console.log(`Current position: ${currentTime} seconds`);

Handling Specific Audio Instances

Howler.js allows you to play multiple instances of the same sound. If you want to seek within a specific instance, you must pass the sound ID (returned by the play() method) as the second argument.

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

// Play returns a unique ID for this instance
const soundId = sound.play();

// Seek to 15 seconds on this specific instance
sound.seek(15, soundId);

Ensuring the Audio is Loaded Before Seeking

Attempting to seek before the audio file has loaded can cause errors or fail silently. To prevent this, always perform the seek operation after the sound has loaded. You can use the onload event or check the state() of the Howl instance.

const sound = new Howl({
  src: ['track.mp3'],
  onload: function() {
    // Audio is loaded, safe to play and seek
    sound.play();
    sound.seek(45);
  }
});

Alternatively, if the sound is already playing, you can use the onplay event to seek once playback begins:

sound.once('play', function() {
  sound.seek(10);
});
sound.play();