Enable background audio

Last update: 2023-10-02

To enable audio playback when app is in background, app should call enableAudioPlaybackInBackground API of MediaPlayer with true as argument when player is in PREPARED state.


App should pause playback when it loses its hold on audio focus during events like responding to the phone, etc. The following code snippet demonstrates how to implement the OnAudioFocusChangeListener:

 * Register the AudioFocus Change listener to track Audio focus from device.
 AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener(){
     public void onAudioFocusChange(int focusChange){
               case AudioManager.AUDIOFOCUS_GAIN:
               case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    /* lower output volume*/
               case AudioManager.AUDIOFOCUS_LOSS:
               case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    if(_lastKnownStatus ==MediaPlayerStatus.PLAYING)

AudioManager audioManager = (AudioManager) getActivity().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

On this page