zmxv / react-native-sound

React Native module for playing sound clips
MIT License
2.78k stars 747 forks source link

[iOS] Ability to resume music, that was playing by other app, interrupted by rn-sound #824

Open polvere94 opened 1 year ago

polvere94 commented 1 year ago

This PR adds the ability to resume playing music interrupted by react-native-sound playing an audio when you want to use playback category with mixWithOthers set to false. This allows to obtain the behavior like the one adopted by Telegram or Whatsapp for voice messages: Music interrupted by the playback of a voice message is resumed when rn-sound stops playing.

To achieve this, I added the AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation option to the function setActive according to the iOS doc Apple doc

Usage: after playing an audio, call the setActive(false, true) function where the last parameter (true) indicates whether you want to notify other apps of the sound deactivation and thus have the app that was interrupted resume playback. The default value is false to not alter the behavior of previous versions

Example:

// Enable playback in silence mode
Sound.setCategory('Playback');

var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  // loaded successfully
  console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());

  // Play the sound with an onEnd callback
  whoosh.play((success) => {
    // do something
    Sound.setActive(false, true);
  });
});