Failure to set AVAudioSession category from background routes audio to random ports, iOS 16

We have a VOIP application. We are setting AudioSession category on appLaunch. Need to support A2Dp profiles.

do {
					try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .spokenAudio, options: [.mixWithOthers, .allowBluetooth, .allowBluetoothA2DP, .duckOthers])
					try AVAudioSession.sharedInstance().setActive(true)
					MCXLogVerbose("[Audio] [App] AVAudioSession activation to playAndRecord SUCCESSFUL")

				}
				catch {
					MCXLogVerbose("[Audio] [App] AVAudioSession activation to playAndRecord FAILED")
				}

We also have a framework which handles everything regarding networking, audio capturing, transmission etc. Apart from the application side, we also need to change category according to necessities. Everything works fine while application is in foreground. But in background state. it seems category can't be set. ERROR: "AVAudioSession.ErrorCode.cannotInterruptOthers", meaning another session is active(i guess). But i could not find any.

As a result, incoming audio sometimes plays at receiver or speaker or airpod randomly, after a single failure.

We are trying to switch category between playAndrecord and playback.

do {
					try AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio, options: [.mixWithOthers, .duckOthers])
					try AVAudioSession.sharedInstance().setActive(true)
					MCXLogVerbose("[Audio] [App] AVAudioSession activation to playback SUCCESSFUL")
				}
				catch {
					MCXLogVerbose("[Audio] [App] AVAudioSession activation to playback FAILED")
				}

** Few confusions here,

  1. Why does it not fail while in foreground?
  2. Why simple straightforward demo application can set category from background without any failure?
  3. It seems iOS15 doesn't create audio routing errors even if session had failed to change its category. Whats changed?
  4. Am i missing any subtle steps to follow?
  5. Also airplay shows wrong port as selected.

**

Failure to set AVAudioSession category from background routes audio to random ports, iOS 16
 
 
Q