How to disable audio playback in Android Chrome when this process is set?

How can I programmatically disable song playback in the background of the Chrome Android process?

Here is a simple example of a page that plays a song in Chrome:

https://thomashunter.name/examples/chrome-audio-bug.html

var song = new Audio('song.ogg');
song.loop = 'loop';

button = document.getElementById('play');

button.addEventListener("click", function() {
  song.play();
});

Notice how the song will continue to play in the background. Although this is good for a jukebox, it will make the player in the web game crazy.

Is there a way to turn off background playback of a single item Audioin Chrome? Or, is there at least a callback when the page loses focus, so I can start song.stop()?

+4
source share
2 answers

visibilitychange:

document.addEventListener('visibilitychange', function(){
    if (document.hidden) {
        // Document is hidden 

        // This re-initialize the audio element
        // to release the audio focus
        song.load(); 
    }
    else {
        // Document is focused
    }
},false);

https://jsfiddle.net/6001wsf9/

Android 5.0 Chrome 43.0.2357.78

+2

API HTML5

    <script>
    var song = new Audio('http://zyu.me:1337/audio/Evasion.ogg');
    song.loop = 'loop';

    button = document.getElementById('play');

    button.addEventListener("click", function() {
      song.play();
    });
var vis = (function(){
    var stateKey, 
        eventKey, 
        keys = {
                hidden: "visibilitychange",
                webkitHidden: "webkitvisibilitychange",
                mozHidden: "mozvisibilitychange",
                msHidden: "msvisibilitychange"
    };
    for (stateKey in keys) {
        if (stateKey in document) {
            eventKey = keys[stateKey];
            break;
        }
    }
    return function(c) {
        if (c) document.addEventListener(eventKey, c);
        return !document[stateKey];
    }
})();
  
  vis(function(){
					
    if(vis()){
        console.log("tab is visible");
		song.play();									
    } else {
	
        console.log("tab is invisible");	
		song.pause();
    }
});
  
  
  </script>
Hide result
+1

All Articles