HTML5 Audio: Music does not stop even after navigating away from the website

Go To StackoverFlow.com

1

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?

2012-04-04 22:11
by Ani
what is zero for? I mean the array? - Ani 2012-04-04 22:13
you mean to say if I have musicvar.src = something.mp3... then I should have musicvar[0].pause()... right - Ani 2012-04-04 22:15
okay... the problem is I'm not initializing this in
@AlienWebguy, you're talking nonsense. Shut up plz - Niet the Dark Absol 2012-04-04 22:35


0

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.

2013-01-21 12:07
by Some Guy


0

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.

2012-04-04 22:34
by Jeffrey Sweeney


0

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).

2012-04-04 23:21
by sc8ing
I had tried using that... but that dint seem to work : - Ani 2012-04-05 18:50
Ads