Skip to content

Commit

Permalink
fix: ensure audio volume is changed in UI thread
Browse files Browse the repository at this point in the history
  • Loading branch information
olivier committed Oct 12, 2023
1 parent 5c3baca commit 6269d83
Showing 1 changed file with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ public ReactExoplayerView(ThemedReactContext context, ReactExoplayerConfig confi
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() {
Expand Down Expand Up @@ -910,9 +910,11 @@ private void releasePlayer() {

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
Expand All @@ -921,6 +923,7 @@ public void onAudioFocusChange(int focusChange) {
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;
Expand All @@ -935,16 +938,21 @@ public void onAudioFocusChange(int focusChange) {
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);
});
}
}
}
Expand Down

0 comments on commit 6269d83

Please sign in to comment.