How to make background audio pause when the web is on background

910 Views Asked by At

The page is mainly for mobile device. In my web AR project I have a background music playing automatically with no control button.

Current issue: When user goes to other app or close the phone it still plays the music just like how Youtube premium works.

What I want: I want the music to stop play automatically when the page is not active on phone. ( user in different app, user close phone)

This is how I added the audio to my project.

html

 <audio id="portal-audio" crossorigin="anonymous" loop="true" preload="auto" src="./assets/music/music.mp3"></audio>

js

   document.getElementById('screen-start').addEventListener('click', function(event) {
        document.getElementById('portal-audio').play();
    })
2

There are 2 best solutions below

0
Alon Shmiel On

You can use visibilitychange:

document.addEventListener("visibilitychange", event => {
  if (document.visibilityState === "visible") {
    console.log("tab is active")
  } else {
    const audio = document.getElementById('portal-audio');
    audio && audio.pause();
    console.log("tab is inactive")
  }
})
2
chleestack On
document.addEventListener("visibilitychange", event => {
  if (document.visibilityState === "visible") {
    document.getElementById('portal-audio').play();
    console.log("tab is active")
  } else {
    const audio = document.getElementById('portal-audio');
    audio && audio.pause();
    console.log("tab is inactive")
  }
})