0

我需要帮助循环播放 HTML5 音频剪辑。

我有以下脚本,但它只播放一次。我需要它在按下链接时播放音乐剪辑并在循环中不停地播放。只有在刷新页面或再次选择链接时才能停止音频:

<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
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(){
html5audio.pause()
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>

谢谢你。

4

1 回答 1

2

你为什么不尝试使用音频标签并添加属性循环,这样它就会背靠背循环

用您自己的音频文件替换 src 以查看它循环

<h1>The audio loop attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls loop>
  <source src="https://www.w3schools.com/tags/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/tags/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

单击此链接以查看其工作

于 2021-08-12T12:50:33.253 回答