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.