问题描述
< audio autoplay ='autoplay'loop = 'loop'id ='audio'controls>
< source src ='http://www.w3schools.com/html/horse.ogg'/>
< source src ='http://www.w3schools.com/html/horse.mp3'/>
< / audio>
现在,当我在iOS设备上播放音频时,它可以很好地循环播放,然而,当我关闭浏览器窗口或切换选项卡时,它只是保持循环,而暂停它的唯一方法是关闭浏览器选项卡。我尝试删除 loop ='loop'
并使用JavaScript,但是这并不奏效,因为结束了
即使浏览器未打开,事件也会触发。
,其中声音是我可以在网上找到的第一个声音,但请注意,我的实际声音很长,所以在浏览器窗口时,确实需要暂停
关闭。
我试过暂停它 onblur
, onunload
和 onbeforeunload
无济于事。有没有办法阻止音频在后台播放?
设法找到解决方案:
利用循环来检查用户是否在网页上。存储时间。
var lastSeen;
var loop = function(){
lastSeen = Date.now();
setTimeout(loop,50);
};
loop();
var music = document.getElementById('music');
music.addEventListener('timeupdate',function(){
if(Date.now() - lastSeen> 100){
this.pause();
}
},false);
这大致就是我的文件的样子。由于 timeupdate
事件在播放音频元素时会持续触发,因此我只需检查最后一次调用循环的时间。如果它被称为超过100毫秒前,我暂停音乐。在我测试的iPad上工作就像一个魅力。
Okay, so I've got something as simple as this:
<audio autoplay='autoplay' loop='loop' id='audio' controls>
<source src='http://www.w3schools.com/html/horse.ogg'/>
<source src='http://www.w3schools.com/html/horse.mp3'/>
</audio>
Now, when I play the audio on an iOS device, it loops fine and everything, however, when I close the browser window, or switch tabs, it just keeps on looping and the only way to pause it is if I shut the browser tab. I tried removing the loop='loop'
and replaying it onended
with JavaScript, but that didn't work either because the ended
event fires even when the browser isn't open.
Demo in which the sound is the first one I could find online, but note that my actual sound is pretty long, so I do need to pause
it when the browser window is closed.
I've tried pausing it onblur
, onunload
and onbeforeunload
to no avail. Is there a way to stop the audio from playing in the background?
Managed to find a solution:
Make use of a loop, to check if the user is on the webpage. Store the time.
var lastSeen;
var loop = function (){
lastSeen = Date.now();
setTimeout(loop, 50);
};
loop();
var music = document.getElementById('music');
music.addEventListener('timeupdate', function (){
if(Date.now() - lastSeen > 100){
this.pause();
}
}, false);
That's roughly what my file looks like. Since the timeupdate
event fires on an audio element continually if it's playing, I only have to check when my loop was last called. If it was called more than 100ms ago, I pause the music. Worked like a charm on the iPad I tested on.
这篇关于关闭iOS Safari时停止循环播放HTML5音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!