Android plugin library that informs unity about audio focus changes. It also has a reliable way of telling if other applications are currently playing music within unity.
Because otherwise unity's fmod implementation will screw up android's AudioManager.html#isMusicActive() and forcing it to lie and it always returns true, even if no music is being played on the device at all.
Now you can enhance the usability for the end-user by muting your application music automatically when the user listens to music in the background while using your app and more importantly automatically turn the music back on, once mp3 player in the background has finished playing.
OnAudioFocusChangeListener.unitypackage
OnAudioFocusChangeListener.jar
Whether you directly import the OnAudioFocusChangeListener.unitypackage asset bundle or you add the files directly:
For the direct approach you will need the 3 files:
Important part is the exchange of the default UnityPlayerNativeActivity by ManualUnityActivity in order to access mUnityPlayer for direct access to unity's fmod player.
And the manifest entry for the focus change listener service.
(Note: Have a look at the demo scene.)
Find out if music is playing:
bool musicIsActive = AndroidMusicHandler.IsMusicActive;
Register a callback listener:
AndroidMusicHandler.RegisterAndroidCallbackListener ((state) => {
var stateText = "";
switch(int.Parse(state)) {
case 1: stateText = "AUDIOFOCUS_GAIN"; break;
case -1: stateText = "AUDIOFOCUS_LOSS"; break;
case -2: stateText = "AUDIOFOCUS_LOSS_TRANSIENT"; break;
case -3: stateText = "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK"; break;
case -4: stateText = "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE"; break;
default: stateText = state; break;
}
Debug.Log(stateText);
});
And finally unregister the callback when you're done.
AndroidMusicHandler.UnregisterAndroidCallbackListener ();
Enjoy. :)
- AndroidMusicHandler.isMusicActive blocks main thread for at least 150ms to start being reliable while unity is active, is there any other way? please let me know! :(
- AndroidMusicHandlerRegisterAndroidCallbackListener will request audio focus and basically mutes background player. This is sadly the only way to actually register a listener to audio focus changes.