Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'

I am running into runtime errors while trying to process microphone audio input, using AVAudioEngine. Here's the code to reproduce:

let bufferSize: AVAudioFrameCount = 2016
let mySampleRate: Double = 8000
let audioFormat = AVAudioFormat(standardFormatWithSampleRate: mySampleRate, channels: 1)

try! AVAudioSession.sharedInstance().setPreferredSampleRate(mySampleRate)
assert(AVAudioSession.sharedInstance().sampleRate == mySampleRate)

engine.inputNode.installTap(onBus: 0, bufferSize: bufferSize, format: audioFormat) { _, _ in
}

try! engine.start()

This crashes at runtime with this error:

Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'

AVAudioSession.sharedInstance().sampleRate is 8000 as per my assert, so that's also what the hardware sample rate should be.

It seems like AVAudioSession.sharedInstance().setPreferredSampleRate(mySampleRate) has no effect.

I spent over an hour going down a rat hole on this. I had worked on a Logic audio session (which was at 48K) with some headphones on and then went over to my iOS simulator to work on my audio code for my app and started getting this crash. Unplugged my headphones, still crashed. Rebooted simulator, deleted app from the simulator, restarted XCode and machine, still crashed. Finally I went to system preference on my mac, selected: Sound & Input, plugged in my headphones so it says "External Microphone", also went to the simulator I/O settings for audio input set to "Internal Microphone", and then my app was able to startup in the simulator without crashing while trying to create an AKMicrophone()...

Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'
 
 
Q