I'm making a game and I would like to detect if something else is already playing music (or starts to play music) as my game is running. If that's the case, I'll fade out the music in the game and keep playing the sound effects. I am using Unity and FMOD for audio playback.
As best I can tell Android provides two different ways to do this: AudioManager.isMusicActive and AudioManager.OnAudioFocusChangeListener.
AudioManager.isMusicActive
does not work for my particular case since it seems the way Unity/FMOD registers itself will make this always return true.
AudioManager.OnAudioFocusChangeListener
lets me detect if another App requests the audio focus, but provides no way of detecting if I can safely request it again.
I have no insight into how Unity/FMOD sets up the audio session, but the default is to play sounds regardless of anything else playing in the background. So, if I only knew if something else was playing this would be easy!
Is there a way to tell if something besides my own app is playing music?
Note: When I say music, it may also be an audiobook, podcast or closest equivalent.
There seems to be a possibility to look for any ongoing media playback notifications, but this requires escalated permissions which seems like too big of an ask for a feature this small.
Here's a few canditates for solutions:
AudioFocusRequest.setAcceptsDelayedFocusGain This can be specified when requesting audio focus, but only really means I don't need focus now, later is also fine. However, if anything else is playing audio that isn't "locked" I will steal audio focus, stopping that and giving me no further information in the process.
AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK initially seemed promising, but as this depends on the other app requesting audio focus to specify itself as transient (ie a notification sound or similar) and provides no benefit to me detecting longer form external audio playback.
BroadcastReceiver/MediaNotifications, here's the Spotify implementation, but as best I can tell this would require specific support inside my app for each player I want to acknowledge, plus the user enabling broadcasts. Might work, but seems brittle.
AudioManager.OnAudioFocusChangeListener
, then useabandonAudioFocusRequest
in the case where there is an audio stream occurring. Parse whatever the current active stream or streams that are playing. Handle playing music depending on the situation then either keep focus or return it to the previous audio source?