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
这篇关于播放音频并单击重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:播放音频并单击重新启动
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
