Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 766
rorypicko Avatar asked Oct 21 '22 21:10

rorypicko


1 Answers

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.

like image 105
Marquizzo Avatar answered Oct 23 '22 15:10

Marquizzo