How can I update a progress bar with howler js?
Asked Answered
U

3

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.

Unreason answered 10/6, 2016 at 13:14 Comment(0)
L
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.

Leung answered 11/6, 2016 at 17:34 Comment(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.Unreason
Are you using 2.0? There is no mute event on 1.x.Leung
Please use requestAnimationFrame as this will perform better when your tab isn't the currently focused tab.Appalachian
R
7

You can use the following snippet

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

function updateWidth() {
  if (sound.playing()) {
    let width = (sound.seek()/sound.duration())*100;
  }
}
Refute answered 2/7, 2020 at 10:4 Comment(1)
I think it should be Multiplied by 100 not divided. let width = (sound.seek()/sound.duration())*100;Chimkent
P
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.

Paranoiac answered 27/3, 2023 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.