How to Implement Skip Ahead and Back in Howler.js

Adding skip forward and backward functionality to an audio player enhances the user experience by allowing quick navigation through tracks. This article provides a straightforward, step-by-step guide on how to implement “skip ahead” and “skip back” features in your web application using the popular Howler.js audio library.

To control the playback position in Howler.js, you use the seek() method. When called without arguments, seek() returns the current playback position in seconds. When passed a numerical argument, it moves the playback to that specific second.

Here is how you can implement skip functionality by retrieving the current position, adding or subtracting your desired interval, and setting the new position.

The Code Implementation

First, initialize your Howler instance:

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

Next, create a function to handle the skip logic. This function will accept a offset value in seconds (positive for skipping forward, negative for skipping backward):

function skip(seconds) {
  // Check if the sound is loaded and playing/ready
  if (sound.state() === 'loaded') {
    const currentTime = sound.seek();
    const duration = sound.duration();
    
    // Calculate the target time
    let targetTime = currentTime + seconds;
    
    // Constrain the target time between 0 and the track duration
    if (targetTime < 0) {
      targetTime = 0;
    } else if (targetTime > duration) {
      targetTime = duration;
    }
    
    // Seek to the new time
    sound.seek(targetTime);
  }
}

Binding to UI Buttons

You can connect this function to HTML buttons using simple event listeners. For example, to skip forward 10 seconds or backward 10 seconds:

<button id="skip-back">10s Back</button>
<button id="skip-forward">10s Forward</button>
document.getElementById('skip-back').addEventListener('click', () => {
  skip(-10);
});

document.getElementById('skip-forward').addEventListener('click', () => {
  skip(10);
});

By retrieving the current seek position, applying your safety boundaries with the track’s duration, and updating the seek position, you successfully implement precise skip controls for Howler.js.