Audio Component Distorted on Mobile App when Game Loses Focus

I’m developing a mobile game and right now I’m testing on an Android OS (Samsung Galaxy S8). I’ve got a master level and two streaming levels. In the master level I have an audio component to play a looping background music (sound cue).

This works fine but when I press the home key on my phone or if the app loses focus in any way the music gets distorted for a second and then shuts off. I’m ok with the music shutting off, ideally all sounds should shut off when the game loses focus. But the distortion right before it shuts off sounds bad.

Is there any way I can catch mobile/Android event for when the home button is clicked or when the game is no longer focused? A few things I’ve tried:

  • Custom GameViewportClient class that catches the LostFocus and ReceivedFocus events. No effect on my issue
  • Catching GameInstance.AppWillTerminate and AppWillEnterBackground. Same as above, no effect
  • Catching GameInstance.AppWillDeactivate. This had a noticeable effect, basically the sound did shut off without distortion but it takes a few seconds after the app has lost focus.

When catching these events I’ve tried both stopping the audio component and setting the volume level to 0. Stopping the audio component doesn’t seem to do anything and setting the volume to 0 only had an effect when used with the AppWillDeactivate event.

An ideal scenario would be catching some sort of lost focus event and stopping the music as an instantaneous transaction - no delay and no distortion. Is there any way to do this?

Also I want to add that the method I thought worked (AppWillDeactivate setting a volume of 0) still has distortion half the time. It’s inconsistent, I really don’t know why the audio doesn’t just shut off entirely.

This issue goes away when you package the game for distribution. I guess when you’re just pushing it to your device it’s still set in “editor” mode.