问题
whenever the code reaches
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {[weak self] (buffer:AVAudioPCMBuffer, when:AVAudioTime)
, app is crashing with following error
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'
I tired removing taps before adding another and I'm making sure I'm not adding more than one tap. what is weird is that the app is working fine with iOS less than 12, and working fine on all simulators.
it is crashing only on real devices with iOS 12. I tried searching for a solution but could't find any thing.
回答1:
This is a sample rate mismatch.
The input node's format can't be changed so you need to match it. installTap
listens to the output of a node, so use inputNode's output format.
inputNode.installTap(onBus: 0, bufferSize: 1024, format: inputNode.outputFormat(forBus: 0))
Another option is to connect the input to a mixer, then tap the mixer using the preferred recording format. Mixers perform implicit sample rate conversions between their inputs and output.
回答2:
The only thing I found that worked to change the sampling rate was
AVAudioSettings.sharedInstance().setPreferredSampleRate(...)
Unfortunately, there is no guarantee that you will get the sample rate that you want, although it seems like 8000, 12000, 16000, 22050, 44100 all worked.
The following did NOT work:
- Setting the my custom format in a tap off engine.inputNode. (Exception, same as OP)
- Adding a mixer with my custom format and tapping that. (Exception)
- Adding a mixer, connecting it with the inputNode's format, connecting the mixer to the main mixer with my custom format, then removing the input of the outputNode so as not to send the audio to the speaker and get instant feedback. (Worked, but got all zeros)
- Not using my custom format at all in the AVAudioEngine, and using AVAudioConverter to convert from the hardware rate in my tap. (Length of the buffer was not set, no way to tell if results were correct)
This was with iOS 12.3.1.
来源:https://stackoverflow.com/questions/53779214/error-when-installing-a-tap-on-audio-engine-input-node