0
votes

I was hoping for some assistance with this. I have 3 audio instances on a single page. Handling the audio to play and pause isn't an issue. The issue is when audio is playing and I click play on another, I can't get the other audio instance to stop playing. So in the end I have these tracks all playing and I have to manual hit stop on each of them. My code below so far.

Honestly I am not sure how to go about doing the checks for this. First time doing something like this.

Any help would be appreciated :) thanks

HTML:

<div class="voting-artist">
    <audio class="audio">
      <source src="{{ song.url }}" type="audio/mpeg">
    </audio>

    <audio class="audio">
      <source src="{{ song.url }}" type="audio/mpeg">
    </audio>

    <audio class="audio">
      <source src="{{ song.url }}" type="audio/mpeg">
    </audio>
</div>

jQuery/JavaScript:

    $votingArtist.each(function(i, value) {

      var $this = $(this);
      var thisAudioPlayBtn = $this.find('.play-btn', $this);
      var thisAudioStopBtn = $this.find('.stop-btn', $this);
      var thisSelectionCont =  $this.find('.selection--play-btn', $this);
      var thisAudio = $this.find('.audio', $this);

      thisAudioPlayBtn.on('click', function(e) {
        thisAudio[0].play();
        thisAudioPlayBtn.hide()
        thisAudioStopBtn.show();
        thisSelectionCont.addClass('is-playing');
       });

       thisAudioStopBtn.on('click', function() {
         thisAudio[0].pause();
         thisAudioPlayBtn.show()
         thisAudioStopBtn.hide();
         thisSelectionCont.removeClass('is-playing');
       });
   });
1

1 Answers

2
votes

Just pause() them all!

thisAudioPlayBtn.on('click', function(e) {
  $("audio").pause();       // Add this to pause them all.
  $(".selection--play-btn").removeClass("is-playing");    // And remove the playing class everywhere too!
  $(".play-btn").hide();    // Reset play/pause button
  $(".stop-btn").show();

  thisAudio[0].play();
  thisAudioPlayBtn.hide()
  thisAudioStopBtn.show();
  thisSelectionCont.addClass('is-playing');
});