2

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();
    })
cybr
  • 51
  • 3

2 Answers2

2

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")
  }
})
Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138
1
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")
  }
})
chleestack
  • 19
  • 1
  • This will be better for the stable operation. Thanks – chleestack Jan 16 '22 at 22:44
  • Hi there. Welcome to StackOverflow. In general, when writing answers on S.O. you may want to elaborate a bit more like why and what you did exactly. Code-only answers are not so welcome. You can read more here: https://stackoverflow.com/help/how-to-answer – F. Müller Jan 16 '22 at 23:07