mardi 31 août 2021

stop audio from playing when another audio starts

this code works perfectly to play random audio files when a button is clicked, what I want. the only problem is that I want the current audio to stop when the button is clicked again so that it is not playing over the next file. any ideas on how to accomplish this would be appreciated!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<audio id="sound0" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound1" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound2" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound3" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>

<button id="button">Click To Play</button>
$( document ).ready(function() {
function playSound(){
  var pattern = [],
    tone;
  pattern.push(Math.floor(Math.random() * 4));
  tone = "#sound" + pattern[0];
  //$(tone).trigger('play');  //uncomment to play
  //$(tone).get(0).play();    //uncomment to play
  $(tone)[0].play();          //comment to turn off
}

$("#button").click(playSound);

});



Aucun commentaire:

Enregistrer un commentaire