0

i want to stop other audio when current one is playing and should be pause by clicking on same button and to be played by clicking on same button plzz help out

<!DOCTYPE HTML>
<html>
  <head>
     <title>Audio</title>
  </head>
  <body>
    <audio id="sound1" src="1.mp3" preload="auto"></audio>
    <button onclick="document.getElementById('sound1').play();">Play it</button>
    <audio id="sound2" src="2.mp3" preload="auto"></audio>
    <button onclick="document.getElementById('sound2').play();">Play it</button>
    <audio id="sound3" src="3.mp3" preload="auto"></audio>
    <button onclick="document.getElementById('sound3').play();">Play it</button>
  </body>
</html>
Santi Gallego
  • 202
  • 1
  • 18
Ashraf
  • 3
  • 9

1 Answers1

0

You can solve this problem by creating a function that takes in the ID of the audio that you want to play (1, 2, or 3), plays it, and pauses the other audio elements:

function playAudio(audioNumber) {
    var audio = document.getElementById('sound' + audioNumber);
    audio.play();
    var notPlaying = [1,2,3];
    notPlaying.splice(notPlaying.indexOf(audioNumber), 1);
    notPlaying.forEach(function(id) {
        document.getElementById('sound' + id).pause();
    });
};

Then run that function each time a button is clicked and pass in their respective IDs

<audio id="sound1" src="1.mp3" preload="auto"></audio>
<button onclick="playAudio(1);">Play it</button>
<audio id="sound2" src="2.mp3" preload="auto"></audio>
<button onclick="playAudio(2);">Play it</button>
<audio id="sound3" src="3.mp3" preload="auto"></audio>
<button onclick="playAudio(3);">Play it</button>
Owen M
  • 2,585
  • 3
  • 17
  • 38