11

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
joshuatvernon
  • 1,530
  • 2
  • 23
  • 45

3 Answers3

10

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.

James Simpson
  • 13,488
  • 26
  • 83
  • 108
7

You can use the following snippet

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

function updateWidth() {
  if (sound.playing()) {
    let width = (sound.seek()/sound.duration())*100;
  }
}
Vikram Sapate
  • 1,087
  • 1
  • 11
  • 16
  • I think it should be Multiplied by 100 not divided. `let width = (sound.seek()/sound.duration())*100;` – Trapcode Jan 24 '22 at 16:14
1

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.

Ben
  • 15,938
  • 19
  • 92
  • 138