Play audio and restart it onclick(播放音频并单击重新启动)
问题描述
我希望在 HTML5 音频播放器中重新启动音频文件.我已经定义了一个音频文件和一个 play
按钮.
I'm looking to restart an audio file in a HTML5 audio player. I have defined a audio file and a play
button.
<audio id="audio1" src="01.wav"></audio>
<button onClick="play()">Play</button>
当我单击 play
按钮时,音频文件开始播放,但是当我再次单击该按钮时,音频文件不会停止并且不会再次播放,直到它到达文件末尾.
When I click the play
button the audio file starts playing, but when I click the button again the audio file doesn't stop and will not play again until it reaches the end of the file.
function play() {
document.getElementById('audio1').play();
}
有没有一种方法可以让我在使用 onclick
单击按钮时重新启动音频文件,而不是等待歌曲停止?
Is there a method that would allow me to restart the audio file when I click the button using onclick
rather than waiting for the song to stop?
推荐答案
要重新播放歌曲,您可以:
To just restart the song, you'd do:
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}else{
audio.currentTime = 0
}
}
FIDDLE
要切换它,就像再次单击时音频停止,而当再次单击时它会从头开始重新启动,您可以执行类似的操作:
To toggle it, as in the audio stops when clicking again, and when click another time it restarts from the beginning, you'd do something more like :
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}else{
audio.pause();
audio.currentTime = 0
}
}
FIDDLE
这篇关于播放音频并单击重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!