Stop if already playing

1.9k views Asked by At

I need some assistance implementing the .playing() method, for when my playSound function is called i want to stop anything that is currently playing, and play the newly requested sound, here is my example which is not stopping each time its called:

  function playSound(audio) {
      var playing;
      var sound = new Howl({
        src: ['assets/sound/voice/' + audio],
        autoplay: false,
        volume: 0.9,
        onplay: function() {
          playing = true;
        },
        onend: function() {
          playing = false;
        }          
      });

      if(playing) {
        sound.stop();
      } else {            
        sound.play();      
      }
  }
1

There are 1 answers

0
Sam T On BEST ANSWER

The solution, in the end, was to create a global variable for "sound":

var sound = null;
function playSound(audio) {
    //check if sound is null, if not stop previous sound and unload it
    if (sound != null) {
        sound.stop();
        sound.unload();
        sound = null;
    }
    sound = new Howl({
        src: ['assets/sound/voice/' + audio]
    });
    sound.play();
}