1

I have developed game is html5,Jquery, Javascript where I need to preload several audios. These audios are playing one by one but, when I minimize iPad then audio is still paying. Can any body help to pause an audio while browser is going to minimize. And audio should play when browser comes to foreground.

neel dhara
  • 41
  • 1
  • 7

3 Answers3

1

I'm about halfway there to getting you a full solution. Here's what I have so far:

var audio = document.getElementsByTagName('audio')[0];
window.onpageshow = function() {
    audio.play();
}
window.onpagehide = function() {
    audio.pause();
}

So, as long as your on the app tab when you close Safari, it will pause the audio. And play it when you start back up. It doesn't stop when you change tabs.

If your app is apple-mobile-web-app-capable, this will trigger onpageshow when you open the app using the homescreen button, and will pause it when you close it. It doesn't pause exactly, since opening it back up forces it to start from the beginning. You'd have to capture where you were in the track using localStorage or something and then set the currentTime to that when you open it back up.

Looks like you'll be able to use the Visibility API in iOS 7 according to caniuse.com

Just for history's sake, I'm going to at least state some other things I tried.

  • window.onblur
  • using requestAnimationFrame with a setTimeout (this worked on desktops, but not iOS)

    var t;
    requestAnimationFrame(function checkWindow() {
        if ( audio.paused ) {
            audio.play();
        }
        clearTimeout(t);
        t = setTimeout(function() {
            audio.pause();
        }, 32);
    });
    
kalley
  • 16,448
  • 2
  • 34
  • 35
1

I recommend you use the page visibility API, which gives you an event that tells you when a page's visibility changes.

function handleVisibilityChange() {
    if (document.hidden){
        stopAllSounds();
    }else{
        playAllSounds();
    }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

stopAllSounds and playAllSounds will be defined as you see fit, but this event will fire when Safari is minimized and maximized. It works on Android devices and all modern platforms

Marquizzo
  • 17,230
  • 9
  • 36
  • 59
0

Hopefully I am not late to answer it. I found the following solution which works in desktop and ios devices (haven't checked in android yet)

$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");

if (prevType != e.type) {   //  reduce double fire issues
    switch (e.type) {
        case "blur":
            // do work
            your_audio.pause();
            break;

        case "focus":
            // do work
            your_audio.play();
            break;
    }
}

$(this).data("prevType", e.type);
})

PS: your_audio is a variable, you have to define it.

I found this solution here

Community
  • 1
  • 1
Jimba Tamang
  • 969
  • 12
  • 15