Get Current Playback Position in Howler.js

Retrieving the current playback position of an audio file in howler.js is a straightforward process using the library’s built-in seek() method. This article provides a direct guide on how to use this method to get the current playback time in seconds, along with a practical code example to track and display the progress of your audio in real-time.

Using the seek() Method

To get the current playback position of a sound, you call the seek() method on your Howl instance without passing any arguments. This returns a float representing the current position in seconds.

Here is a basic example:

// Initialize the Howl instance
const sound = new Howl({
  src: ['audio.mp3']
});

// Play the sound
sound.play();

// Get the current playback position (returns seconds, e.g., 14.25)
const currentPosition = sound.seek();
console.log('Current Position:', currentPosition);

Handling Multiple Sound Instances

If you are playing multiple sounds simultaneously from a single Howl instance, you should pass the specific soundId to the seek() method to get the correct position for that specific playback:

const soundId = sound.play();

// Get the position of the specific sound ID
const currentPosition = sound.seek(soundId);

Tracking Playback Position in Real-Time

Because howler.js does not trigger a continuous event during playback, you need to use a loop to track the position in real-time. You can achieve this using requestAnimationFrame for smooth updates, which is ideal for progress bars or timers.

const sound = new Howl({
  src: ['audio.mp3'],
  onplay: function() {
    // Start tracking when the audio plays
    requestAnimationFrame(updateProgress);
  }
});

function updateProgress() {
  if (sound.playing()) {
    const currentTime = sound.seek();
    console.log(`Playback progress: ${currentTime.toFixed(2)} seconds`);
    
    // Continue updating
    requestAnimationFrame(updateProgress);
  }
}

sound.play();