You need to enable JavaScript to run this app. 如何为HTML5 audio添加循环播放功能?现有脚本仅支持单次播放
优惠活动
大模型
产品
解决方案
定价
更多

如何为HTML5 audio添加循环播放功能?现有脚本仅支持单次播放

实现循环播放+点击切换启停的修改方案

核心修改点

  • 创建audio元素时添加loop属性,开启原生循环播放能力
  • 重写playclip方法逻辑,改为播放/暂停切换:当音频处于播放状态时点击就暂停,未播放时点击就重置进度后循环播放
  • 利用HTML5 Audio原生的paused属性判断当前播放状态,无需额外定义变量

完整修改后代码

<a href="#music" onclick="clicksound.playclip()" style="cursor: default;">Link here</a>

<script>
// Sound for background music
var html5_audiotypes={
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}

function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
// 新增:开启循环播放
html5audio.loop = true
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
// 修改:切换播放/暂停逻辑
html5audio.playclip=function(){
if(!html5audio.paused){
// 正在播放则暂停
html5audio.pause()
}else{
// 未播放则重置进度后播放
html5audio.currentTime=0
html5audio.play()
}
}
return html5audio
}
else{
return {playclip:function(){throw new Error("")}}
}
}

//Initialize two sound clips with 1 fallback file each:

var mouseoversound=createsoundbite("music.ogg", "music.mp3")
var clicksound=createsoundbite("music.ogg", "music.mp3")
</script>

效果说明

  • 首次点击链接:音频从头开始循环播放
  • 再次点击链接:音频立即暂停
  • 刷新页面后音频自动停止,完全符合需求

内容的提问来源于stack exchange,提问作者Timothy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 16:57:05