- Home /
Audio playing at inappropriate times on Android due to OnApplicationPause
I've been experiencing problems with audio playing at inappropriate times on Android, like when the App is not in focus or on the unlock screen of the phone. It seems that eventhough I've got Run In Background unchecked the game is in fact on at times in the background. The easiest way to reproduce it is by quickly turning the phone's screen on and off while the game is running. This gets the phone to its unlock screen but with the sound of my game playing in the background. A logging of OnApplicationPause and OnApplicationFocus tells me that the game indeed is unpaused in the background.
Am I missing something or is this be a Unity bug? As it is now it leaves me to make some sort of global muting system, which feels like a weird solution to something that should be handled by the Unity player the problem is unmuting since I cannot listen to OnApplicationPause(true) as this obviously is triggered at the wrong time.
I had a very similar issue on an Android tablet. I could never get OnApplicationFocus() to trigger; anytime I lost focus on the app, my logs always showed OnApplicationPaused() was being triggered.
For OnApplicationPaused(), are you checking if the boolean parameter is true before running code to pause the audio? If so, try running your code to pause the audio regardless of the parameter's state. $$anonymous$$y issue was that the audio seemed to be correctly pausing as the game first lost focus, but when I resumed the app, the audio began playing again. Once I called for my audio to pause regardless of whether OnApplicationPaused() was showing true or false, the audio correctly paused.
I'm only able to test on a $$anonymous$$indle Fire at the moment, and haven't seen OnApplicationFocus() trigger yet. Which device are you testing on?
I'm on a Nexus S and the same thing happens to me, no OnApplicationFocus, only OnApplicationPause.
Your suggestion with not listening to the parameter is interesting, but how would you know when to unmute it, when you actually DO want to unmute it?
@$$anonymous$$rten, when OnApplicationPause calls, I bring up a pause menu and mute my background audio track. Then, once I click the 'resume' button, I turn my audio back on.
Is it mostly just background music you're having the issue with? If so, you can try muting it when OnApplicationPause triggers (regardless of the boolean state) and then be sure to turn it back on once you click resume (or however you allow your game to continue after being paused). If you have a more complicated setup and you're trying to mute/unmute specific audio tracks, I'm not entirely sure this solution will work cleanly for you.
Answer by kromenak · Dec 03, 2011 at 12:57 AM
This should have been fixed in the latest Unity release - at least, it was fixed for us. See http://unity3d.com/unity/whats-new/unity-3.4.2