iosswiftsfspeechrecognizer

While in a phone call or Facetime session, attempting to use SpeechRecognizer crashes app


The scenario described in the title will produce the following error:

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

After that, I am dumped into app delegate and not given much help into what went wrong.

I am familiar with the need to properly end an audio session, but in my particular situation, this would happen when starting the session, in particular here:

node.installTap(onBus: bus, bufferSize: 1024, format: recordingFormat) { buffer, _ in
    request.append(buffer)
}

Solution

  • The culprit here can be seen by tracing my function back by one step to this line:

    let recordingFormat = node.outputFormat(forBus: bus)
    

    Since the microphone is allocated to another app (in my situation, Facetime), it is unable to gain access to it for the function posted in the question where the crash occurs.

    I found that by monitoring the sampling rate, I can determine if I have exclusive access to it or not.

    if recordingFormat.sampleRate == 0.0 {
        throw(MyAwesomeError.audioInUse)
    }
    

    When the value is 0.0, it is in use. When the value is 44100.0, then I am in business.

    By placing the above check just before the node.installTap(...) function, I can safely avoid the crash and then use my existing error handling code to notify the user of the situation.

    Putting everything together, it looks like this:

    let recordingFormat = node.outputFormat(forBus: bus)
    if recordingFormat.sampleRate == 0.0 {
        throw(MyAwesomeError.audioInUse)
    }
    node.installTap(onBus: bus, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        request.append(buffer)
    }