'multiple html5 audio players play control

I have multiple HTML5 audio players on my page, the problem is that when I play both of them they play simultaneously overlapping each other's sound. Basically what I want to do is that one player is playing and another is clicked for play the previous one stops playing.

Following is my html

  <div>
     <audio controls="controls">
         <source src="./public/audio/tiesto.mp3" type="audio/mpeg">
     </audio>
  </div>
  <div>
     <audio controls="controls">
          <source src="./public/audio/123.mp3" type="audio/mpeg">
     </audio>
 </div>

This is my js which I copied from somewhere but not sure how it applies to the audio element.

var curPlaying;
$(function () {
    $(".playback").click(function (e) {
        e.preventDefault();
        var song = $(this).next('audio')[0];
        if (song.paused) {
            if (curPlaying) {
                $("audio", "#" + curPlaying)[0].pause();
            }
            song.play();
            curPlaying = $(this).parent()[0].id;
        } else {
            song.pause();
            curPlaying = null;
        }
    });
});

The guys was using a custom play button whereas I want to use the ausio control and it's built in functionality. Is it possible?



Solution 1:[1]

Simply added the following javascript to my custom js

window.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    } 
    window.$_currentlyPlaying = evt.target;
}, true);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amin Baig