Skip to content

Commit

Permalink
fix: handle Android 15+ restriction on audio focus requests
Browse files Browse the repository at this point in the history
Do not attempt to play sounds if audio focus request failed

See: https://developer.android.com/about/versions/15/behavior-changes-15#audio-focus

"Apps that target Android 15 (API level 35) must be the top app or running a
foreground service in order to request audio focus. If an app attempts to request
focus when it does not meet one of these requirements, the call returns AUDIOFOCUS_REQUEST_FAILED"
  • Loading branch information
mikehardy committed Sep 21, 2024
1 parent 301e649 commit c5e5d23
Showing 1 changed file with 14 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import androidx.annotation.CheckResult
import androidx.annotation.VisibleForTesting
import androidx.media.AudioFocusRequestCompat
import androidx.media.AudioManagerCompat
Expand Down Expand Up @@ -130,10 +131,14 @@ class SoundTagPlayer(private val soundUriBase: String, val videoPlayer: VideoPla
return continuation.resumeWithException(exception)
}

requestAudioFocus()
continuation.ensureActive()
Timber.d("starting sound tag")
start()
if (requestAudioFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
continuation.ensureActive()
Timber.d("starting sound tag")
start()
} else {
Timber.d("unable to get audio focus, cancelling work")
continuation.cancel()
}
}
}

Expand Down Expand Up @@ -187,14 +192,15 @@ class SoundTagPlayer(private val soundUriBase: String, val videoPlayer: VideoPla
prepare()
}

private fun requestAudioFocus() {
@CheckResult
private fun requestAudioFocus(): Int {
Timber.d("Requesting audio focus")
AudioManagerCompat.requestAudioFocus(audioManager, audioFocusRequest)
return AudioManagerCompat.requestAudioFocus(audioManager, audioFocusRequest)
}

private fun abandonAudioFocus() {
private fun abandonAudioFocus(): Int {
Timber.d("Abandoning audio focus")
AudioManagerCompat.abandonAudioFocusRequest(audioManager, audioFocusRequest)
return AudioManagerCompat.abandonAudioFocusRequest(audioManager, audioFocusRequest)
}
}

Expand Down

0 comments on commit c5e5d23

Please # to comment.