From 0bfbda66e40a017745584007efe30db95f0f399e Mon Sep 17 00:00:00 2001 From: Olivier Bouillet <62574056+freeboub@users.noreply.github.com> Date: Wed, 18 Oct 2023 22:45:19 +0200 Subject: [PATCH] fix(android): ensure audio volume is changed in UI thread (#3292) Co-authored-by: olivier --- .../exoplayer/ReactExoplayerView.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index 1005ec95..34e8790b 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -281,7 +281,7 @@ public class ReactExoplayerView extends FrameLayout implements audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); themedReactContext.addLifecycleEventListener(this); audioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(themedReactContext); - audioFocusChangeListener = new OnAudioFocusChangedListener(this); + audioFocusChangeListener = new OnAudioFocusChangedListener(this, themedReactContext); } private boolean isPlayingAd() { @@ -908,9 +908,11 @@ public class ReactExoplayerView extends FrameLayout implements private static class OnAudioFocusChangedListener implements AudioManager.OnAudioFocusChangeListener { private final ReactExoplayerView view; + private final ThemedReactContext themedReactContext; - private OnAudioFocusChangedListener(ReactExoplayerView view) { + private OnAudioFocusChangedListener(ReactExoplayerView view, ThemedReactContext themedReactContext) { this.view = view; + this.themedReactContext = themedReactContext; } @Override @@ -919,6 +921,7 @@ public class ReactExoplayerView extends FrameLayout implements case AudioManager.AUDIOFOCUS_LOSS: view.hasAudioFocus = false; view.eventEmitter.audioFocusChanged(false); + // FIXME this pause can cause issue if content doesn't have pause capability (can happen on live channel) view.pausePlayback(); view.audioManager.abandonAudioFocus(this); break; @@ -933,16 +936,21 @@ public class ReactExoplayerView extends FrameLayout implements break; } - if (view.player != null) { + Activity activity = themedReactContext.getCurrentActivity(); + if (view.player != null && activity != null) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // Lower the volume if (!view.muted) { - view.player.setVolume(view.audioVolume * 0.8f); + activity.runOnUiThread(() -> { + view.player.setVolume(view.audioVolume * 0.8f); + }); } } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // Raise it back to normal if (!view.muted) { - view.player.setVolume(view.audioVolume * 1); + activity.runOnUiThread(() -> { + view.player.setVolume(view.audioVolume * 1); + }); } } }