HTML5音频:即使在离开网站后,音乐也不会停止 [英] HTML5 Audio: Music does not stop even after navigating away from the website

查看:313
本文介绍了HTML5音频:即使在离开网站后,音乐也不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML5制作手机游戏。在游戏过程中有一个背景音乐,一旦我导航到另一个页面,理想情况下应该停止...逻辑在老款iPhone和Android上正常运行。
但是,在iPhone 4和iPad上,音乐不会停止并继续播放(即使我导航到另一个网站),直到浏览器关闭。
当然在代码和卸载处理程序中有一个

I'm making a mobile game using HTML5. There is a background music that runs during the gameplay and should ideally stop once I navigate to another page... The logic works properly on older iPhones and android. However, on iPhone 4 and iPads the music doesn't stop and continues to play (even when I navigate to another website) until the browser is closed. Of course there is a call

music_var.pause()

函数调用...但这似乎不起作用。
关于这里发生了什么的任何想法?

function in the code as well as the unload handler... but this simply doesn't seem to work. Any ideas on what is happening here?

推荐答案

管理找到解决方案,如我在这里发布了

Managed to find a solution, as I've posted here

使用循环来检查用户是否是在网页上。存储时间。

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() - exports.lastSeen > 100){
        this.pause();
    }
}, false);

这大致与我的档案相似。由于timeupdate事件在播放时会不断触发音频元素,因此我只需检查上次调用循环的时间。如果超过100毫秒之前调用它,我会暂停音乐。在我测试的iPad上工作就像魅力一样。

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.

这篇关于HTML5音频:即使在离开网站后,音乐也不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆