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);
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.
There are all sorts of discrepancies with the audio
tag, and some browsers will not even pause
when told to (add that to not issuing callbacks properly, preloading, or even working).
To circumvent this problem, you could set the volume
parameter to 0
before pausing.
Try using onbeforeunload to stop the music since when safari on iphones is playing music the music will continue to play in the background even when the app is exited (sort of like how music can play in the background). If you double tap the home button, hold down on the Safari icon until a minus button appears, and tap the minus the music should stop. This is because the older iphones probably arent running iOS4 or above (which has multitasking and can play safari's music in the background even while it isn't running).