Error when installing a tap on audio engine input node

2.2k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

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:

  1. Setting the my custom format in a tap off engine.inputNode. (Exception, same as OP)
  2. Adding a mixer with my custom format and tapping that. (Exception)
  3. 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)
  4. 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.