javascripttypescriptrxjshtml5-audiohowler.js

Does howler have a way of notifying given an interval?


Wondering if Howler JS has a way of notifying every second? This would be used to update a state variable that tracks how long a song has been playing for. One way to do it is like this:

var sound = new Howl({
  xhr: {
    method: 'POST',
    headers: {
      Authorization: 'Access-Control-Allow-Origin:*',
    },
    withCredentials: true,
  },
  //  autoplay: true,
  loop: true,
  volume: 1,
  format: ['mp3'],
  src: [mp3],
});
sound.play();
let position: number = 0;
const s = interval(1000).subscribe((v) => {
  console.log(v);
  if (!sound.playing()) {
    s.unsubscribe();
  }
  position = sound.seek();
  console.log(position);

Just curious if howler has something like:

const interval = 1000;
song.on(interval, callback)

So that would call the callback until the song is done playing?


Solution

  • As stated in the docs, Howler instances have a method .on to listen to events. Sadly, there is no progression event or similar.

    However, there is an option html5 that can be set to true in order to force the use of HTML5 for playback.

    A call to Howler#play returns the Sound's ID. In your case:

    const soundId = sound.play(); // your variable sound is an Howler instance
    

    You can get the Sound object by calling Howler#_soundById.

    const soundObj = sound._soundById(soundId);
    

    You can get the HTML5 audio element by using the Sound#_node property (which will be an HTMLAudioElement).

    const audio = soundObj._node;
    

    Then you can use whatever HTMLAudioElement provides, including listening to progress events.

    fromEvent(audio, "progress")
      .pipe(throttleTime(1000))
      .subscribe(event => {
        // do stuff with `audio` and `event` here
      });