Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 245
Christiaan de Groot Avatar asked Mar 12 '26 06:03

Christiaan de Groot


1 Answers

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
});
like image 98
semanser Avatar answered Mar 13 '26 21:03

semanser