How can I stop audio

Hi can I ask some help please in my page I have 10 audios, I use the HTML 5 audio tag, my problem when I play the audio1 and play audio2, the audio1 will not stop. What I want is when the audio2 is playing the audio1 will stop automatically. Is this possible ?

     <audio >
              <source src="path to my audio1" type="audio/ogg">
               <source src="path to my audio1" type="audio/mpeg">
                                      
      </audio>
       <audio >
         <source src="path to my audio2" type="audio/ogg">
          <source src="path to my audio2" type="audio/mpeg">
                                       
       </audio>
           <audio >
                  <source src="path to my audio3" type="audio/ogg">
                  <source src="path to my audio3" type="audio/mpeg">
                                       
           </audio>                               

Try putting this before your </body> tag:

<script>
var players = document.querySelectorAll("audio");

function playClicked(event) {
  for (let z = 0; z < players.length; z++) {
    if (event.target !== players[z]) {
      players[z].pause();
    }
  }
}

for (let z = 0; z < players.length; z++) {
  players[z].addEventListener("play", playClicked);
}
</script>
2 Likes

Thank you so much it works :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.