AVAudioEngine exception - required condition is false format.sampleRate == hwFormat.sampleRate

I see in Crashlytics few users are getting this exception when connecting the inputNode to mainMixerNode in AVAudioEngine:

   Fatal Exception: com.apple.coreaudio.avfaudio
   required condition is false:
   format.sampleRate == hwFormat.sampleRate

Here is my code:

    self.engine = AVAudioEngine()
    
    let format = engine.inputNode.inputFormat(forBus: 0)
    
    //main mixer node is connected to output node by default
    engine.connect(self.engine.inputNode, to: self.engine.mainMixerNode, format: format)

Just want to understand how can this error occur and what is the right fix?

The most common cause of errors like this is that the audio device format (input or output) changed at an unexpected time. Make sure that you register for engine configurations changes:

https://developer.apple.com/documentation/avfaudio/avaudioengineconfigurationchangenotification/

and reconfigure your engine connections as needed when you receive that notification.

As suggested by @Polyphonic, I observed avaudioengineconfigurationchangenotification . But some of the users are seeing the same crash but now it happens on the following line:

let format = engine.inputNode.inputFormat(forBus: 0)

Here is the backtrace:

Fatal Exception: com.apple.coreaudio.avfaudio
0  CoreFoundation                 0x99288 __exceptionPreprocess
1  libobjc.A.dylib                0x16744 objc_exception_throw
2  CoreFoundation                 0x170488 -[NSException initWithCoder:]
3  AVFAudio                       0x9f64 AVAE_RaiseException(NSString*, ...)
4  AVFAudio                       0xc99e0 AVAudioIONodeImpl::SetOutputFormat(unsigned long, AVAudioFormat*)
5  AVFAudio                       0x91b0 -[AVAudioNode setOutputFormat:forBus:]
6  AVFAudio                       0x20e4 AVAudioEngineImpl::UpdateInputNode(bool)
7  AVFAudio                       0xe12b0 -[AVAudioEngine inputNode]
AVAudioEngine exception - required condition is false format.sampleRate == hwFormat.sampleRate
 
 
Q