Christiaan de Groot
Christiaan de Groot

Reputation: 33

When audio finished, show play button again?

I'm a real nooby haha and can't figure this out on my own.

When I load the page, it shows the play button. I hit play (music starts playing) and the pause button is showing for whenever I like to pause the music.

But when the music is finished playing it keeps showing me the pause button.

Question; how can I get the play button back whenever the music is finished playing?

var audio, playbtn, mutebtn, seek_bar;
function initAudioPlayer(){
	audio = new Audio();
	audio.src = "./audio/D.mp3";
	audio.loop = false;
	// Set object references
	playbtn = document.getElementById("playpausebtn");
	// Add Event Handling
	playbtn.addEventListener("click",playPause);
	// Functions
	function playPause(){
		if(audio.paused){
		    audio.play();
		    playbtn.style.background = "url(./images/pause.png) no-repeat";
	    } else {
		    audio.pause();
		    playbtn.style.background = "url(./images/play.png) no-repeat";
	    }
	}
}
window.addEventListener("load", initAudioPlayer);
	<button id="playpausebtn"></button>

Upvotes: 3

Views: 241

Answers (1)

semanser
semanser

Reputation: 2348

You need to add an event listener for ended event and run the logic you want inside that.

The ended event is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.

More info about this event here.

audio.addEventListener("ended", function(){
     // show play button
});

Upvotes: 4

Related Questions