user10082163
user10082163

Reputation: 25

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>  

Upvotes: 2

Views: 402

Answers (2)

David Archibald
David Archibald

Reputation: 1528

You are currently only have an event listener for clicks on your button playAudio. You need a second event listener for when the audio has ended playing. In this case it is simply the ended event, which you need to attach to your audio variable with addEventListener.

Below is the the code I would use.

// This part is just a refactored version of your current code.
var audio = document.getElementById('testAudio');
var playButton = document.getElementById('playAudio');
playButton.addEventListener('click', function() {
    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();
    }
});

// This runs when the audio ends and will change the `playButton`'s text to be "PLAY VOICE AUDIO"
audio.addEventListener('ended', function() {
    playButton.innerHTML = 'PLAY VOICE AUDIO';
    playButton.className = '';
}

I would also suggest learning some ES6(the newest JavaScript version), but I have left the code as is.

Upvotes: 0

displayName
displayName

Reputation: 1106

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

Upvotes: 1

Related Questions