How to pause and start audio when switching tab in browser?

0

On Google's Oskar Fischinger's 117th Birthday Doodle I realized that it is when I change the tab , the music stops playing, and when you return to the page again, it continues to play. I created an example using <audio> . See:

<audio controls>
  <source src="http://www.zedge.net/d2w/4/1631039/878827377/view/?mp3"type="audio/mpeg">
Your browser does not support the audio element.
</audio>

How to pause and start audio when tab switch?

    
asked by anonymous 23.06.2017 / 18:23

2 answers

0

This code should help you, it is quite simple to understand and just replace an audio video player, but any way:

When leaving the tab the code is called:

if (currentTab == '') {
   //Find current tab:
   currentTab = $('#tabs ul li.active').find('a').attr('href');
}

//Stop playing video:
if (currentTab != '')
   $('div#' + currentTab).find('iframe').attr('src', '');

and returning to the tab:

var index = $(this).attr('id');
$('div#' + currentTab).find('iframe').attr('src', urls[index]);
    
23.06.2017 / 18:37
0

Try using pageVisibility - w3c

A more or less example of what it would look like:

    window.addEventListener('visibilitychange', () => {
       if (document.hidden) {
         console.log('PAUSAR O AUDIO');
       }else {
         console.log('PLAY NO AUDIO');
       }
    });
    
28.06.2017 / 16:45