Search code examples
javascriptiosipadmobile-safari

Audio on Safari Mobile when power button is pressed


I'm relatively new to JavaScript and I'm working on a game build for Safari Mobile on iPad (iOS 10.2.1).

When the game is launched a background music is played (as in any other game on the market). If the game page loses focus, the music is stopped and it won't play until the page gets focus again.

If a new tab is called or the browser is closed, no issue happens, but if the user presses power button or close iPad smart cover and puts the device in pause mode, an unusual behavior occurs: the music stops, but audio file is somehow passed to Music App, appearing visible and playable (look at the screenshot below).

iPad unlock screen

I've tried to unset audio variable onblur event doing:

backgroundMusic = new Audio("pathToAudio");
window.addEventListener("blur", function(e) {
   delete backgroundMusic;
}

var backgroundMusic = new Audio("pathToAudio");
window.addEventListener("blur", function(e) {
   backgroundMusic = null;
}

var backgroundMusic = new Audio("pathToAudio");
window.addEventListener("blur", function(e) {
   backgroundMusic = (function(){}());
}

Looking at JavaScript way to unset variable on stackoverflow:

How to unset a JavaScript variable?

How to unset variable using javascript?

How to delete a variable?

But nothing works... How could I prevent this behavior from happening?

!!! Please, no answear in jQuery !!!


Solution

  • It was not possible to unset my audio, but I was able to prevent the strange behavior by changing the path to the audio file on blur event.

    backgroundMusic.src = "";
    

    On focus, it is possible to set the path back to the original one.