Handling ExoPlayer Audio Focus Loss When Resuming Video in Android App

161 Views Asked by At

I'm encountering an issue with audio focus in my Android app using ExoPlayer. The scenario is as follows:

  1. A video is playing in my app.
  2. I switch to a browser (e.g., Chrome) and start playing a video (Let's say Live News From AajTak/NDTV News channel website)there, which pauses my app's video.
  3. When I switch back to my app and resume the video, it plays for a fraction of a second and then stops, citing PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS as the reason.
  4. Interestingly, the video in the browser has already paused.

This issue seems to occur even with other apps like YouTube (Play video in Youtube and then do above steps....YouTube video also stop after some time automatically), where they lose audio focus in a similar manner.

I'm looking for insights or solutions on how to handle this audio focus transition smoothly in my app. Is there a way to ensure stable audio focus regain in my app when resuming the video?

Any suggestions or advice on handling this audio focus issue effectively would be greatly appreciated.

2

There are 2 best solutions below

1
DC_Androidista On

Kindly mention your device's Android version as well as Exoplayer version you are using.

Checked this issue with Youtube app. Its reproduceable. To get over this issue, there may be following solutions:

  1. For rooted devices, you may use adb force stop command to stop the other app, of course with the help of PackageManager
  2. For unrooted devices, you may have to involve user to do one of the following: i. Stop video playbacks in recent apps he/she has opened OR ii. Force stop recent app(s) where they watched a video. You may do this by showing a dialog or beautiful screen with the message

This is difficult to fully control from developer side until the fix comes from Android framework level(I think).

1
deeppandya On

You can try to create AudioAttributes as below,

val audioAttributes: AudioAttributes = AudioAttributes.Builder()
        .setUsage(C.USAGE_MEDIA)
        .setContentType(C.CONTENT_TYPE_MOVIE)
        .build()

And set AudioAttributes as mentioned below when you create exoplayer instance using builder,

setAudioAttributes(audioAttributes, true //Handle auto focus)

Here i am mentioning full solution that works great,

val audioAttributes: AudioAttributes = AudioAttributes.Builder()
        .setUsage(C.USAGE_MEDIA)
        .setContentType(C.CONTENT_TYPE_MOVIE)
        .build()
val player = ExoPlayer.Builder(this)
        .setMediaSourceFactory(mediaSourceFactory)
        .setHandleAudioBecomingNoisy(true).setWakeMode(C.WAKE_MODE_LOCAL)
        .setAudioAttributes(audioAttributes, true).build()