Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable Audio Playback in Android Chrome when the process is Backgrounded?

How can I programmatically disable a song from playing in the background of a Chrome Android process?

Here's a simple example of a page which 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 keep playing in the background. While nice for a jukebox, it'll drive a player of a web game insane.

Is there a way to disable background playing of a single Audio element in Chrome? Or, is there at least a callback for when the page loses focus so I could run song.stop()?

like image 265
Thomas Hunter II Avatar asked Sep 27 '22 20:09

Thomas Hunter II


People also ask

How do I stop Google Chrome from playing sound?

Turn off sounds in Chrome by right-clicking on the tab and selecting the Mute Site option. If you aren't sure which tab is making the noise, look for a little speaker icon on the offending tab. To mute Safari sounds, look for the speaker icon in the address bar.


1 Answers

You can try to use 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);

The complete example is available here https://jsfiddle.net/6001wsf9/

Tested on Android 5.0 with Chrome 43.0.2357.78

like image 50
Mattia Maestrini Avatar answered Oct 03 '22 03:10

Mattia Maestrini