I want to play audio when I click to image. But when I click another image are playing both. I need to stop or pause first sound to play the new sound.
I don’t want to use <audio>
tag in html as soon as possible; not for something special just to get the challenge.
I am trying this:
HTML:
<div class="container">
<div class="box">
<img id="beach" src="./images/beach.jpeg" alt="" >
</div>
<div class="box">
<img id="river" src="./images/river.jpg" alt="">
</div>
<div class="box">
<img id="mountains" src="./images/mountain.jpg" alt="">
</div>
<div class="box">
<img id="rain" src="./images/rain.jpg" alt="">
</div>
<div class="box">
<img id="jungle" src="./images/jungle.png" alt="">
</div>
<div class="box">
<img id="fire" src="./images/fire.jpeg" alt="">
</div>
</div>
Javascript:
window.addEventListener('load',
function () {
let images = document.querySelectorAll("img");
images.forEach(image =>{
image.addEventListener("click", playAudio);
})
}, false);
function playAudio (event){
let imgName = event.currentTarget.id;
let audioPlay = new Audio(`./sounds/${imgName}.wav`);
audioPlay.onloadedmetadata = function (eSound){
eSound.currentTarget.loop = true;
eSound.currentTarget.play()
}
console.log(event)
}
2
Answers
Create a variable, e.g.
currentAudio
, to check if there is audio playing. When the audio starts, set thecurrentAudio
to the audio target, then when you call the function again it checks to see if it is set to null if it is not then it will stop the audio and reset it to nullyou can use check variable for this to keep track whether audio is playing or not,
example –