Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

How to turn off audio when mobile screen is locked

Discussion in 'Project Tiny' started by Odele, Mar 20, 2019.

  1. Odele

    Odele

    Joined:
    Jun 3, 2015
    Posts:
    8
    Hello everyone

    I'm trying to stop audio when the user does not focus on the game with this code

    Code (JavaScript):
    1.  window.addEventListener('focus', () => {
    2.               const audio = this.world.getConfigData(ut.Audio.AudioConfig);
    3.               audio.paused = false;
    4.               this.world.setConfigData(audio);
    5.             });
    6.  
    7.             window.addEventListener('blur', () => {
    8.               const audio = this.world.getConfigData(ut.Audio.AudioConfig);
    9.               audio.paused = true;
    10.               this.world.setConfigData(audio);
    11.             });
    but it doesn't work when the screen is locked, the audio keeps playing.
     
  2. Odele

    Odele

    Joined:
    Jun 3, 2015
    Posts:
    8
    In case anyone has the same problem with me here is the solution

    Code (JavaScript):
    1. document.addEventListener('visibilitychange', () => {
    2.   const audio = this.world.getConfigData(ut.Audio.AudioConfig);
    3.   if(document.hidden){
    4.     audio.paused = true;
    5.   } else {
    6.     audio.paused = false;
    7.   }
    8.   this.world.setConfigData(audio);
    9.   this.scheduler.run();
    10. });
     
  3. Sly88

    Sly88

    Joined:
    Feb 22, 2016
    Posts:
    73
    how to use this code in Tiny TypeScript System class?
     
  4. Odele

    Odele

    Joined:
    Jun 3, 2015
    Posts:
    8
    I try to call this once on onUpdate (in initialize state).

    Code (JavaScript):
    1. OnUpdate(): void {
    2.    const context = world.getConfigData(Context);
    3.    switch(context.state){
    4.       case State.Initialize:
    5.          callEventListener();
    6.          context.state = State.Gameplay;
    7.          break;
    8.    }
    9. }
    hope this can help