音频播放后重置按钮文本

Reset button text after audio plays

我有一个按钮,当您单击带有文本 "PLAY VOICE AUDIO" 的 playAudio 时,该按钮会播放音频文件,并且文本会更改为 "PAUSE VOICE"。如果您在播放时再次单击 playAudio(现在文本为 "PAUSE VOICE"),它会暂停。

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

提前感谢您的帮助!

<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>  
var audio = document.getElementById('testAudio');
var btn = document.getElementById("playAudio");
audio.addEventListener('ended', function() {
 btn.innerHTML = "PLAY VOICE AUDIO";
 btn.className = "";
});

您目前只有一个事件侦听器用于点击您的按钮 playAudio。当 audio 结束播放时,您需要第二个事件侦听器。在这种情况下,它只是 ended 事件,您需要使用 addEventListener.

将其附加到 audio 变量

下面是我要使用的代码。

// 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 = '';
}

我还建议学习一些 ES6(最新的 JavaScript 版本),但我保留了原样的代码。