Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

howler.js play sound at a specific position

Hi I would like to start playing a sound on a scecific position. The api said that I can use .pos but it doesn't start where I would like it to start

  <p>This sound last 13 sec.</p>
  <h1>Audio</h1>
  <h3><a href="#" class="val2">2:00</a></h3>
  <h3><a href="#" class="val3">3:00</a></h3>
  <h3><a href="#" class="val4">4:00</a></h3>
  <h3><a href="#" class="val20">10:00</a></h3>

My javascript.

var son = [false, "0000"]

sound = new Howl({
    urls: ['http://goldfirestudios.com/proj/howlerjs/sound.mp3'],
    autoplay: false
    });

function playSequence(events,valeur){

  //if there is no sound play the track at a certain position
  var playSound = function(valeur){
    if(son[0] == true){
      sound.stop();
      son[0] = false;
    }else{
      son[0] = true;
      sound.pos = parseInt(valeur[0]); // position at 2 sec
      sound.play();
    }
  }
   playSound(valeur);
}

//play the sound on click
$("a.val2").on('click', function(events){
    valeur = $(this).text();
    playSequence(events, valeur);
    });
like image 782
Papouche Guinslyzinho Avatar asked Oct 17 '25 14:10

Papouche Guinslyzinho


2 Answers

pos is a method, not a property. For best compatibility, you would want to play it like follows (fixed in the 2.0 beta branch):

sound.play(function(id){
    sound.pos(valeur[0], id);
});

Here's how you would do it in 2.0 (check 2.0 branch at https://github.com/goldfire/howler.js):

var id = sound.play();
sound.seek(valeur[0], id);

If you are only playing one sound then there is no need to set the id, but it is best practice to change the position after playing when using 1.1.x.

like image 89
James Simpson Avatar answered Oct 19 '25 02:10

James Simpson


I was having issues playing a sound at a specific time as well, it worked on the first play of a sound, but if I tried to go back and play that sound again, using seek immediately wouldn't work.

I just figured out a way to consistently make it work using howler v2:

function playSoundAtPosition(sound, pos) {
  sound.once("play", () => {
    sound.seek(pos);
  });
  sound.play();
}

This makes use of the callback method once which fires the callback to the play event and then immediately removes itself. I believe this helps because it waits until it actually knows the sound is playing before seeking to the desired time.

I know this is an old question but hopefully it's useful to someone if they come across this!

like image 35
Chris Sandvik Avatar answered Oct 19 '25 02:10

Chris Sandvik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!