简体   繁体   中英

Stop HTML5 audio from playing when device is locked (Android & iOS)

I'm developing a HTML5 game that has looping music and sound effects. I'm using the soundjs library from the createjs suite .

When I minimize the browser on Android devices and iOs devices the sounds continue to play. This is even the case when the device is locked! This is also the case cross browser, (Safari, Chrome, Android Native, Firefox)

Is there a simple fix for this, or is detecting the page being inactive and disabling the sounds a more likely solution?


I tried this, thinking that the timeout would fire when the page was closed but it doesn't. :(

var timeout = -1;
setInterval(function(){
     if(timeout!=-1) clearTimeout(timeout);
     timeout = setTimeout(function(){
         AudioManager.setMute(true);
     }, 200);
, 100);

What worked for me is the following (using jQuery v2.1.4):

// Declare soundtrack as SoundJS object
soundtrack = createjs.Sound.play("main", {loop: -1});

$(window).focus(function() {
    // Unpause when window gains focus
    soundtrack.paused = false;
}).blur(function() {
    // Pause when window loses focus
    soundtrack.paused = true;
});

Whenever the Safari window loses focus, it'll pause the soundtrack. When it regains focus, it'll resume. Worked for me on iPhone Safari iOS 9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM