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);
});
new Audio() and play that one.const sounds = [
"https://s3.amazonaws.com/freecodecamp/simonSound1.mp3",
"https://s3.amazonaws.com/freecodecamp/simonSound2.mp3",
"https://s3.amazonaws.com/freecodecamp/simonSound3.mp3",
"https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"
];
const audio = new Audio();
function playSound(){
const rand = Math.floor(Math.random() * sounds.length);
audio.src = sounds[rand];
audio.play();
}
document.querySelector("#button").addEventListener("click", playSound);
<button id="button">Click To Play</button>
If you want to listen to "ended" and play another audio file, just use:
audio.addEventListener("ended", playSound);
A non jQuery solution:
var sound0 = document.getElementById("sound0");
var sound1 = document.getElementById("sound1");
sound1.onplay = function() {
sound0.pause();
}
What this code does is that whenever sound1 audio starts playing It pauses the sound0 audio.