required condition is false: IsFormatSampleRateAndChannelCountValid(format)

Viewed 4198

iOS speech kit,the SFSpeechRecognizer and AVAudioEngine work together to speech recognition, crash sometime when the mic is used by other progress.

        self.audioEngine = [[AVAudioEngine alloc] init];
        AVAudioInputNode *inputNode = self.audioEngine.inputNode;
        AVAudioFormat *nativeAudioFormat = [inputNode outputFormatForBus:0];
        __weak typeof(self)weakSelf = self;
        [inputNode installTapOnBus:0 bufferSize:1024 format:nativeAudioFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
            [weakSelf.recognitionRequest appendAudioPCMBuffer:buffer];
        }];
        [self.audioEngine prepare];
        [self.audioEngine startAndReturnError:&error];

Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: IsFormatSampleRateAndChannelCountValid(format)'

1 Answers

How are you setting your AVAudioSession? This error is usually caused when that isn't set properly.

That is, you need to call the below code (or similar according to your use-case) before each time you use the mic to ensure the audio session is set up properly. If it isn't, for example, you are using the .playback category and try to use the microphone, you'll get the IsFormatSampleRateAndChannelCountValid(format) crash.

let audioSession = AVAudioSession.sharedInstance()
do {
  try audioSession.setCategory(.playAndRecord, options: .defaultToSpeaker)
  try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
catch let error as NSError {
  print("ERROR:", error)
}
Related