Search code examples
javascriptaudiomp3innerhtmlplayback

Reset button text after audio plays


I have a button that plays an audio file when you click playAudio with the text "PLAY VOICE AUDIO", and the text is changed to "PAUSE VOICE". It pauses if you click playAudio again(now with the text "PAUSE VOICE") when playing.

I would like the button text to go back to the "PLAY VOICE AUDIO" once the audio file has finished playing.

Thanks for any help in advance!

<div class="center">
    <button id="playAudio">PLAY VOICE AUDIO</button>
</div>

<audio id="testAudio" hidden src="testaudioagainmp3.mp3" type="audio/mpeg"></audio>    


<!-- Play/pause audio script -->
<script>
document.getElementById("playAudio").addEventListener("click", function() {
    var audio = document.getElementById('testAudio');
    if(this.className == 'is-playing') {
        this.className = "";
        this.innerHTML = "PLAY VOICE AUDIO"
        audio.pause();
    } else {
        this.className = "is-playing";
        this.innerHTML = "PAUSE VOICE";
        audio.play();
    }
});
</script>  

Solution

  • var audio = document.getElementById('testAudio');
    var btn = document.getElementById("playAudio");
    audio.addEventListener('ended', function() {
     btn.innerHTML = "PLAY VOICE AUDIO";
     btn.className = "";
    });