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

Asked

Viewed 77 times

0

On the Google Doodle of 117th anniversary of Oskar Fischinger I realized that when you change the tab, the music stops playing, and when you go back to the page again, it keeps playing. I created an example using <audio>. Behold:

<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 switching tab?

  • In that reply there are the Focus and Blur methods. That when leaving the page you are pausing the video or audio through the Blur, and when back to focus is called the Focus there you continue to run your video or audio.

2 answers

0

That code should help you, it is quite simple to understand and just replace a video player by audio, but anyway:

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 back to the tab:

var index = $(this).attr('id');
$('div#' + currentTab).find('iframe').attr('src', urls[index]);

0

Try to use the pageVisibility - w3c

An example more or less of how it would be:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.