Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions android/src/main/java/com/zmxv/RNSound/RNSoundModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ public class RNSoundModule extends ReactContextBaseJavaModule implements AudioMa
Boolean mixWithOthers = true;
Double focusedPlayerKey;
Boolean wasPlayingBeforeFocusChange = false;
AudioManager audioManager;

public RNSoundModule(ReactApplicationContext context) {
super(context);
this.context = context;
this.category = null;
audioManager = (AudioManager) context.getApplicationContext().getSystemService(context.AUDIO_SERVICE);
}

private void setOnPlay(boolean isPlaying, final Double playerKey) {
Expand Down Expand Up @@ -204,7 +206,7 @@ protected MediaPlayer createMediaPlayer(final String fileName) {
}
return mediaPlayer;
}

File file = new File(fileName);
if (file.exists()) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Expand Down Expand Up @@ -237,12 +239,14 @@ public void play(final Double key, final Callback callback) {

// Request audio focus in Android system
if (!this.mixWithOthers) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

this.focusedPlayerKey = key;
} else {
audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
player.setVolume(0.2f, 0.2f);
}
this.focusedPlayerKey = key;

final RNSoundModule that = this;

player.setOnCompletionListener(new OnCompletionListener() {
boolean callbackWasCalled = false;
Expand All @@ -251,6 +255,11 @@ public void play(final Double key, final Callback callback) {
public synchronized void onCompletion(MediaPlayer mp) {
if (!mp.isLooping()) {
setOnPlay(false, key);

if (that.mixWithOthers && key == that.focusedPlayerKey) {
audioManager.abandonAudioFocus(that);
}

if (callbackWasCalled) return;
callbackWasCalled = true;
try {
Expand Down Expand Up @@ -303,7 +312,6 @@ public void stop(final Double key, final Callback callback) {

// Release audio focus in Android system
if (!this.mixWithOthers && key == this.focusedPlayerKey) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(this);
}

Expand All @@ -328,7 +336,6 @@ public void release(final Double key) {

// Release audio focus in Android system
if (!this.mixWithOthers && key == this.focusedPlayerKey) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(this);
}
}
Expand Down