gpt4 book ai didi

javascript - 如何使用 jQuery 无限循环播放音频文件

转载 作者:行者123 更新时间:2023-11-27 23:39:21 25 4
gpt4 key购买 nike

现在我有一段代码(如下),它允许我在单击按钮时播放音频文件。但是,我想让文件无限循环播放,直到单击“停止”按钮。我怎样才能实现这一目标?

var audiotypes={
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}

function ss_soundbits(sound){
var audio_element = document.createElement('audio')
if (audio_element.canPlayType){
for (var i=0; i<arguments.length; i++){
var source_element = document.createElement('source')
source_element.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
source_element.setAttribute('type', audiotypes[RegExp.$1])
audio_element.appendChild(source_element)
}
audio_element.load()
audio_element.playclip=function(){
audio_element.pause()
audio_element.currentTime=0
audio_element.play()
}
return audio_element
}
}

var audio = ss_soundbits('audio/file.mp3');

var start_audio= function() {
audio.playclip();
};

最佳答案

捕获音频元素上的 ending 事件,然后使其再次播放。

audio_element.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);

这对您来说应该足够了。

编辑

正如@A所指出的。沃尔夫,我犯了一个疏忽,点击停止会触发结束的事件。设置全局 bool 标志将解决此问题。

var stopped = false;

audio_element.addEventListener('ended', function() {
if(!stopped){
this.currentTime = 0;
this.play();
}
}, false);

var stop_button = document.getElementByID('stop');

stop.addEventListener('click', function(){
stopped = true
audio_element.stop();
});

关于javascript - 如何使用 jQuery 无限循环播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33833774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com