I have assigned a single icon for both play and pause. If it clicks one-time song will play and again clicked song should pause. But the issue is song gets played but not getting paused.
var flag=0;
document.querySelector(".play").addEventListener("click",function(){
if(flag==0)
{
alert("button clicked");
var sng=new Audio("music/1.mp3");
sng.play()
flag=1;
}
else
{
sng.pause();
flag=0;
}
})
CodePudding user response:
Your sng
variable isn't reachable inside the else
clause. Declare it in the top scope:
var flag = 0;
var sng = new Audio("music/1.mp3");
document.querySelector(".play").addEventListener("click", function() {
if (flag == 0) {
alert("button clicked");
sng.play()
flag = 1;
} else {
sng.pause();
flag = 0;
}
})
Or this tidied up version that accomplishes the same thing:
const sng = new Audio("https://cdn.pixabay.com/download/audio/2022/05/27/audio_1808fbf07a.mp3?filename=lofi-study-112191.mp3");
const playButton = document.querySelector(".play")
const toggleSong = () => sng.paused ? sng.play() : sng.pause()
playButton.addEventListener("click", () => toggleSong())
<button >Play/pause</button>