当您单击带有文本“ PLAY VOICE AUDIO”的playAudio
时,我有一个播放音频文件的按钮,并且文本更改为“ PAUSE VOICE”。如果在播放时再次单击playAudio
(现在带有文本“ PAUSE VOICE”),它将暂停。
音频文件播放完毕后,我希望按钮文字回到“ PLAY VOICE AUDIO”。
感谢您的任何帮助!
<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>
答案 0 :(得分:1)
var audio = document.getElementById('testAudio');
var btn = document.getElementById("playAudio");
audio.addEventListener('ended', function() {
btn.innerHTML = "PLAY VOICE AUDIO";
btn.className = "";
});
答案 1 :(得分:0)
您当前只有一个事件监听器,用于单击按钮playAudio
。当audio
结束播放时,您需要第二个事件侦听器。在这种情况下,这只是ended
事件,您需要使用audio
将其附加到addEventListener
变量。
下面是我要使用的代码。
// 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版本),但是我将代码保留了。