Random crash from AVFAudio library

Hi everyone ! I'm getting random crashes when I'm using the Speech Recognizer functionality in my app. This is an old bug (for 8 years on Apple Forums) and I will really appreciate if anyone from Apple will be able to find a fix for this crashes. Can anyone also help me please to understand what could I do to keep the Speech Recognizer functionality still available in my app, but to avoid this crashes (if there is any other native library available or a CocoaPod library).

Here is my code and also the crash log for it.

Code:

func startRecording() {    
    startStopRecordBtn.setImage(UIImage(#imageLiteral(resourceName: "microphone_off")), for: .normal)
    if UserDefaults.standard.bool(forKey: Constants.darkTheme) {
        commentTextView.textColor = .white
    } else {
        commentTextView.textColor = .black
    }
    commentTextView.isUserInteractionEnabled = false
    recordingLabel.text = Constants.recording
    
    if recognitionTask != nil {
        recognitionTask?.cancel()
        recognitionTask = nil
    }
    
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSession.Category.record)
        try audioSession.setMode(AVAudioSession.Mode.measurement)
        try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    } catch {
        showAlertWithTitle(message: Constants.error)
    }
    
    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
    
    let inputNode = audioEngine.inputNode
    
    guard let recognitionRequest = recognitionRequest else {
        fatalError(Constants.error)
    }
    
    recognitionRequest.shouldReportPartialResults = true
    
    recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
        
        var isFinal = false
        
        if result != nil {
            
            self.commentTextView.text = result?.bestTranscription.formattedString
            isFinal = (result?.isFinal)!
        }
        
        if error != nil || isFinal {
            self.audioEngine.stop()
            inputNode.removeTap(onBus: 0)
            
            self.recognitionRequest = nil
            self.recognitionTask = nil
            
            self.startStopRecordBtn.isEnabled = true
        }
    })
    
    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {[weak self] (buffer: AVAudioPCMBuffer, when: AVAudioTime) in // CRASH HERE
        self?.recognitionRequest?.append(buffer)
    }
    
    audioEngine.prepare()
    
    do {
        try audioEngine.start()
    } catch {
        showAlertWithTitle(message: Constants.error)
    }
}

Here is the crash log:

Thanks for very much for reading this !

And here is the crash log:

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: SIGNAL 6 Abort trap: 6
Terminating Process:  [4954]

Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x1a1e6ab28 __exceptionPreprocess + 164 (NSException.m:249)
1   libobjc.A.dylib                 0x199cb6f78 objc_exception_throw + 60 (objc-exception.mm:356)
2   CoreFoundation                  0x1a1ef0234 +[NSException raise:format:arguments:] + 96 (NSException.m:0)
3   AVFAudio                        0x1bb856a84 AVAE_RaiseException(NSString*, ...) + 52 (AVAEInternal.h:69)
4   AVFAudio                        0x1bb8b8c78 AUGraphNodeBaseV3::CreateRecordingTap(unsigned long, unsigned int, AVAudioFormat*, void (AVAudioPCMBuffer*, AVAudioTime*) block_pointer) + 760 (AVAEGraphNode.mm:832)
5   AVFAudio                        0x1bb930f1c -[AVAudioNode installTapOnBus:bufferSize:format:block:] + 1420 (AVAudioNode.mm:185)
6                                   0x104b4eed8 InspectionCommentsVC.startRecording() + 1700 (InspectionCommentsVC.swift:278)
7                                   0x104b503c0 specialized InspectionCommentsVC.startStopMicrophoneBtn(_:) + 256 (InspectionCommentsVC.swift:198)
8                                   0x104b4e474 InspectionCommentsVC.startStopMicrophoneBtn(_:) + 4 (<compiler-generated>:0)
9                                   0x104b4e474 @objc InspectionCommentsVC.startStopMicrophoneBtn(_:) + 48
10  UIKitCore                       0x1a4e2bf78 -[UIApplication sendAction:to:from:forEvent:] + 100 (UIApplication.m:5595)
11  UIKitCore                       0x1a47c0698 -[UIControl sendAction:to:forEvent:] + 112 (UIControl.m:920)
12  UIKitCore                       0x1a47c0a10 -[UIControl _sendActionsForEvents:withEvent:] + 324 (UIControl.m:991)
13  UIKitCore                       0x1a47bdf0c -[UIButton _sendActionsForEvents:withEvent:] + 124 (UIButton.m:4173)
14  UIKitCore                       0x1a47bfa78 -[UIControl touchesEnded:withEvent:] + 400 (UIControl.m:670)
15  UIKitCore                       0x1a41fb4c0 -[UIWindow _sendTouchesForEvent:] + 776 (UIWindow.m:3330)
16  UIKitCore                       0x1a41fae64 -[UIWindow sendEvent:] + 3204 (UIWindow.m:3658)
17  UIKitCore                       0x1a41fa0e4 -[UIApplication sendEvent:] + 560 (UIApplication.m:12689)
18  UIKitCore                       0x1a41bc970 __dispatchPreprocessedEventFromEventQueue + 5552 (UIEventDispatcher.m:2598)
19  UIKitCore                       0x1a41bb010 __processEventQueue + 5544 (UIEventDispatcher.m:2956)
20  UIKitCore                       0x1a41b9a1c updateCycleEntry + 160 (UIEventDispatcher.m:126)
21  UIKitCore                       0x1a40a4d78 _UIUpdateSequenceRun + 84 (_UIUpdateSequence.mm:119)
22  UIKitCore                       0x1a40a4468 schedulerStepScheduledMainSection + 144 (_UIUpdateScheduler.m:1037)
23  UIKitCore                       0x1a40a4524 runloopSourceCallback + 92 (_UIUpdateScheduler.m:1186)
24  CoreFoundation                  0x1a1db562c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1957)
25  CoreFoundation                  0x1a1db48a8 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001)
26  CoreFoundation                  0x1a1db3058 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2038)
27  CoreFoundation                  0x1a1db1d88 __CFRunLoopRun + 828 (CFRunLoop.c:2955)
28  CoreFoundation                  0x1a1db1968 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
29  GraphicsServices                0x1e60a74e0 GSEventRunModal + 164 (GSEvent.c:2196)
30  UIKitCore                       0x1a4224edc -[UIApplication _run] + 888 (UIApplication.m:3692)
31  UIKitCore                       0x1a4224518 UIApplicationMain + 340 (UIApplication.m:5282)
32                                  0x104b9d170 main + 64 (AppDelegate.swift:15)
33  dyld                            0x1c52d2d84 start + 2240 (dyldMain.cpp:1298)

Kernel Triage:
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter

Hello, thanks for pasting the code + crash you're hitting, but please take a few extra minutes and paste this issue into a bug report so we can confirm this is tracked in our internal system. You can file a report here: https://developer.apple.com/bug-reporting/

Once you do, feel free to reply with the Feedback ID number.

It seems I do get the same crash on my iOS code. I could not reproduce it, but get between 1 and 4 crashes from every 200 user sessions. Any hints on how to solve this issue would be highly appreciated.

Here is my code (very similar to code shown above):

    private func transcribe() {
        guard let recognizer, recognizer.isAvailable else {
            print("--- SpeechRec.transcribe - SpeechRecognizer TRANSCRIBE ERROR: \(RecognizerError.recognizerIsUnavailable)")
            return
        }
                
        do {
            if let audioEngine {
                let request = SFSpeechAudioBufferRecognitionRequest()
                request.shouldReportPartialResults = true
                request.requiresOnDeviceRecognition = false // might fix speechRec error 1101 in console
                
                let audioSession = AVAudioSession.sharedInstance()
                try audioSession.setCategory(.playAndRecord, mode: .measurement, policy: .default, options: .duckOthers)
                try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
                
                let inputNode = audioEngine.inputNode
                let recordingFormat = inputNode.outputFormat(forBus: 0)
                inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, _) in
                    request.append(buffer)
                }

                try audioEngine.start()
                
                self.recognitionTask = recognizer.recognitionTask(with: request, delegate: self)

            } else {
                
                let (audioEngine, request) = try Self.prepareEngine()
                self.audioEngine = audioEngine
                self.request = request
                
                self.recognitionTask = recognizer.recognitionTask(with: request, delegate: self)
                
            }
        } catch {
            Logger.audio.error("--- SpeechRec.transcribe - SpeechRecognizer AudioSession/AudioEngine ERROR: \(error)")
            self.reset()
        }
    }

This is the backtrace that the Organizer shows in Xcode:

Last Exception Backtrace (0)
#0	(null) in __exceptionPreprocess ()
#1	(null) in objc_exception_throw ()
#2	(null) in +[NSException raise:format:arguments:] ()
#3	(null) in AVAE_RaiseException(NSString*, ...) ()
#4	(null) in AVAudioIONodeImpl::SetOutputFormat(unsigned long, AVAudioFormat*) ()
#5	(null) in AUGraphNodeBaseV3::CreateRecordingTap(unsigned long, unsigned int, AVAudioFormat*, void (AVAudioPCMBuffer*, AVAudioTime*) block_pointer) ()
#6	(null) in -[AVAudioNode installTapOnBus:bufferSize:format:block:] ()
#7	0x100d34e10 in SpeechRecognizer.transcribe() at /Users/klaus/Developer/ScriptBuddy/ScriptBuddy/Assistants/SpeechRecognizer.swift:245
#8	0x100d34298 in SpeechRecognizer.startTranscribing(andCompareTo:) at /Users/klaus/Developer/ScriptBuddy/ScriptBuddy/Assistants/SpeechRecognizer.swift:167
#9	(null) in Script.speakNextScriptElement() ()
#10	0x100d43bfc in specialized SpeechSynthesizer.speechSynthesizer(_:didFinish:) at /Users/klaus/Developer/ScriptBuddy/ScriptBuddy/Assistants/SpeechSynthesizer.swift:942
#11	(null) in SpeechSynthesizer.speechSynthesizer(_:didFinish:) ()
#12	(null) in @objc SpeechSynthesizer.speechSynthesizer(_:didFinish:) ()
#13	(null) in -[AVSpeechSynthesizer(PublicSpeechImplementation) processSpeechJobFinished:successful:] ()
#14	(null) in -[AVSpeechSynthesizer(PublicSpeechImplementation) _handleSpeechDone:successful:] ()
#15	(null) in __67-[AVSpeechSynthesizer(PublicSpeechImplementation) _speakUtterance:]_block_invoke_6 ()
#16	(null) in __46-[TTSSpeechManager _speechJobFinished:action:]_block_invoke ()
#17	(null) in _dispatch_call_block_and_release ()
#18	(null) in _dispatch_client_callout ()
#19	(null) in _dispatch_main_queue_drain ()
#20	(null) in _dispatch_main_queue_callback_4CF ()
#21	(null) in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#22	(null) in __CFRunLoopRun ()
#23	(null) in CFRunLoopRunSpecific ()
#24	(null) in GSEventRunModal ()
#25	(null) in -[UIApplication _run] ()
#26	(null) in UIApplicationMain ()
#27	(null) in closure #1 in KitRendererCommon(_:) ()
#28	(null) in runApp<A>(_:) ()
#29	(null) in static App.main() ()
#30	(null) in static ScriptBuddyApp.$main() ()
#31	(null) in main ()
#32	(null) in start ()
Random crash from AVFAudio library
 
 
Q