'flutter: IOS - how can I make Audioplayers duck external music, instead of stop it?

I know that iOS assigns only one audio session to all plugins in the same app. So in my app, I record and play voice-messages. It is possible that a user might be playing music on another app while using my app; so my app needs to duck the external music while I play or record a voicenote (i.e my app should not stop external music, but duck it, and then continue it when the voice message is finished).

I've tried to use the "audio_session" plugin to set up an iOS audio session to duck external music; and activate that audio session right before playing the voice-message using "AudioPlayers"; but it seems that when the voice-message starts playing, the plugin overrides the audio_session settings and stops external music.

Heres some code:

I use audio_session plugin to configure the session like so:

Future configurePlayOnlySession() async {
    sessionPO = await AudioSession.instance;
    myOptions = AVAudioSessionCategoryOptions.duckOthers;
    myNotify = AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation;

await sessionPO.configure(AudioSessionConfiguration(
  avAudioSessionCategory: AVAudioSessionCategory.playback,
  avAudioSessionCategoryOptions: myOptions,
  avAudioSessionMode: AVAudioSessionMode.spokenAudio,
  avAudioSessionRouteSharingPolicy:
      AVAudioSessionRouteSharingPolicy.defaultPolicy,
  avAudioSessionSetActiveOptions: myNotify,
  androidAudioAttributes: const AndroidAudioAttributes(
    contentType: AndroidAudioContentType.speech,
    flags: AndroidAudioFlags.none,
    usage: AndroidAudioUsage.voiceCommunication,
  ),
  androidAudioFocusGainType: AndroidAudioFocusGainType.gainTransientMayDuck,
  androidWillPauseWhenDucked: false,
));

print("Audio configuration complete");
}

then I activate the session before playing the audio like so:

    if (await sessionPO.setActive(true)) { //If I pause here then external music ducks
  await audioCache.play( //But once I call this, external music is stopped
    'beep.wav',
  );
}

After calling setActive on sessionPO, external music ducks perfectly. But then when I play the sound, external music stops. It's like the Audioplayer overrides the sessionPO configuration.



Solution 1:[1]

While looking at flutter_sound documentation here, I came across this which I think might solve your problem:

if (Platform.isIOS)
    await flutterSoundPlayer.iosSetCategory( t_IOS_SESSION_CATEGORY.PLAY_AND_RECORD, t_IOS_SESSION_MODE.DEFAULT, IOS_DUCK_OTHERS |  IOS_DEFAULT_TO_SPEAKER );

See the link I shared for more details

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tonder