12

How can I use howler js and update the progress bar as the audio plays?

I assume I use either pos or seek however I can't seem to get it working.

Can I create a on event listener to change every time the position changes?

Progress bar HTML:

<progress id="progress_bar" value="0.0" max="1.0" style="-webkit-appearance: none; appearance: none; height: 48px; float: left;"></progress>

Howler js:

on ('update_progress', function() {
    document.getElementById('progress_bar').value = audio.pos();
}),

and then how can I update the position of the audio if the progress bar is pressed. I think I might actually be better served using an input range in that case.

3 Answers 3

11

There is currently no progress event in howler.js, though it may get added at a later date. However, you can get the current position by calling audio.seek() at any time (on 2.0) or audio.pos() on 1.0. You could then either call this in requestAnimationFrame (this is what the 2.0 demos use) or setInterval to update your progress bar.

3
  • Will look into this and post my result. May I ask also what the syntax is for custom on event. I thought it was this on("mute", function()); but it doesn't seem to work. Commented Jun 12, 2016 at 9:43
  • Are you using 2.0? There is no mute event on 1.x. Commented Jun 12, 2016 at 17:35
  • 1
    Please use requestAnimationFrame as this will perform better when your tab isn't the currently focused tab. Commented Feb 26, 2018 at 9:14
7

You can use the following snippet

setInterval(() => {
  updateWidth(); 
},300);

function updateWidth() {
  if (sound.playing()) {
    let width = (sound.seek()/sound.duration())*100;
  }
}
1
  • I think it should be Multiplied by 100 not divided. let width = (sound.seek()/sound.duration())*100;
    – Trapcode
    Commented Jan 24, 2022 at 16:14
2

Similar to Vikram's answer, but using requestAnimationFrame instead of setInterval.

// Set a play callback for the howl
howl.on("play", () => {

    // Reference
    let updateRaf = undefined;

    // Define a function to be run on every animation frame
    const onAnimationFrame = () => {

        // If the howl is still playing
        if (howl.playing()) {

            // Calculate the width
            const width = (howl.seek() / howl.duration()) * 100;

            // Continue processing updates
            updatedRaf = requestAnimationFrame(onAnimationFrame);
        }

        // If the howl is no longer playing
        else {

            // Stop processing updates
            if (updatedRaf) {
                cancelAnimationFrame(updatedRaf);
            }
        }
    };

    // Start processing updates
    updatedRaf = requestAnimationFrame(onAnimationFrame);
});

Note: Not tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.