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
这篇关于播放音频并单击重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:播放音频并单击重新启动


基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01