When to set AVAudioSession's preferredInput?

I want the audio session to always use the built-in microphone. However, when using the setPreferredInput() method like in this example

private func enableBuiltInMic() {
    // Get the shared audio session.
    let session = AVAudioSession.sharedInstance()
    
    // Find the built-in microphone input.
    guard let availableInputs = session.availableInputs,
          let builtInMicInput = availableInputs.first(where: { $0.portType == .builtInMic }) else {
        print("The device must have a built-in microphone.")
        return
    }
    
    // Make the built-in microphone input the preferred input.
    do {
        try session.setPreferredInput(builtInMicInput)
    } catch {
        print("Unable to set the built-in mic as the preferred input.")
    }
}

and calling that function once in the initializer, the audio session still switches to the external microphone once one is plugged in. The session's preferredInput is nil again at that point, even if the built-in microphone is still listed in availableInputs.

So,

  1. why is the preferredInput suddenly reset?
  2. when would be the appropriate time to set the preferredInput again?

Observing the session’s availableInputs did not work and setting the preferredInput again in the routeChangeNotification handler seems a bad choice as it’s already a bit too late then.

Probably way too late but perhaps someone else will benefit from the discussion.

I have observed that the system will always jump to the recently plugged-in microphone. I assume this is because they assume that a person who just plugged in a microphone wants to use said microphone immediately.

My suggestion is to monitory the route change notifications and re-assert your wishes by calling setPreferredInput again. I have not tested this but give it a try.

When to set AVAudioSession's preferredInput?
 
 
Q