Random AVAudioEngine crash

I am seeing a random crash on the AVAudioEngine startAndReturnError method call. I am not able to reproduce this but I am getting a lot of crash reports from the application on the store. My application mix audio from mulitiple files which I pretty much copy the code from the sample project UsingAVAudioEngineforPlaybackMixingandRecording. I tried to add try-catch block to the call and it does not seem to catch the exception. Any ideas or suggestion on how to debug this? It happens across device models (iPhone, iPad, iPod) and iOS (8 and 9)




Thread : Fatal Exception: com.apple.coreaudio.avfaudio

0 CoreFoundation 0x23d9468b __exceptionPreprocess

1 libobjc.A.dylib 0x35292e17 objc_exception_throw

2 CoreFoundation 0x23d94561 +[NSException raise:format:]

3 libAVFAudio.dylib 0x22652c21 AVAE_RaiseException(NSString*, ...)

4 libAVFAudio.dylib 0x22665dd5 AVAudioEngineGraph::PerformCommand(AUGraphNode&, AVAudioEngineGraph::ENodeCommand, void*, unsigned long) const

5 libAVFAudio.dylib 0x226669e3 AVAudioEngineGraph::Initialize()

6 libAVFAudio.dylib 0x226a3cc3 AVAudioEngineImpl::Initialize()

7 libAVFAudio.dylib 0x226a2bdf AVAudioEngineImpl::Start(NSError**)

8 libAVFAudio.dylib 0x226a2b53 -[AVAudioEngine startAndReturnError:]

9 Acapella 0x000bd98b __33-[MCAudioMixer initWithMetadata:]_block_invoke (MCAudioMixer.m:182)

10 Foundation 0x24b48b39 __22-[__NSObserver _doit:]_block_invoke

11 Foundation 0x24b4c80d __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__

12 Foundation 0x24aae217 -[NSBlockOperation main]

13 Foundation 0x24aa04e1 -[__NSOperationInternal _start:]

14 Foundation 0x24b4eac5 __NSOQSchedule_f

15 libdispatch.dylib 0x35994d17 _dispatch_client_callout

16 libdispatch.dylib 0x359a30b1 _dispatch_main_queue_callback_4CF$VARIANT$mp

17 CoreFoundation 0x23d579ad __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__

18 CoreFoundation 0x23d55ea7 __CFRunLoopRun

19 CoreFoundation 0x23ca9249 CFRunLoopRunSpecific

20 CoreFoundation 0x23ca9035 CFRunLoopRunInMode

21 GraphicsServices 0x2cd5bad1 GSEventRunModal

22 UIKit 0x27ebe8a9 UIApplicationMain

23 Acapella 0x0015fc63 main (main.m:14)

24 libdyld.dylib 0x359de873 start

Post not yet marked as solved Up vote post of iami2 Down vote post of iami2
4.6k views

Replies

No messages of any sort in the system log?


-DS

Not sure how to check for "messages in the system log" but I am seeing this as part of the crash log. Does this help?


Fatal Exception: com.apple.coreaudio.avfaudio

error 561017449

Well, that translates to AVAudioSessionErrorInsufficientPriority (AVAudioSession.h) but it shouldn't lead to a crash.


Can you please file a bug for this crasher and attach a test case that reproduces the issue.


thank you.

Hello, I've the same issue.


App records and trim audio like this:


NSString *trimmedAudioFilePath = [SSTalkingManager stringPathFile];//[NSString stringWithFormat:@"%@/%@.wav", DOCUMENTS_FOLDER, kFileName];

NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:trimmedAudioFilePath]) {

NSError *error;

if ([fileManager removeItemAtPath:trimmedAudioFilePath error:&error] == NO) {

NSLog(@"removeItemAtPath %@ error:%@", trimmedAudioFilePath, error);

}

}


NSLog(@"Saving to %@", trimmedAudioFilePath);


AVAsset *avAsset = [AVAsset assetWithURL:self.audioRecorder.url];

NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];

AVAssetTrack *track = [tracks objectAtIndex:0];


AVAssetExportSession *exportSession = [AVAssetExportSession

exportSessionWithAsset:avAsset

presetName:AVAssetExportPresetAppleM4A];


/

CMTime startTime = CMTimeMake(self.recordingBeginTime*SAVING_SAMPLES_PER_SECOND, SAVING_SAMPLES_PER_SECOND);

CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, kCMTimePositiveInfinity);


/

AVMutableAudioMix *exportAudioMix = [AVMutableAudioMix audioMix];

AVMutableAudioMixInputParameters *exportAudioMixInputParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];

exportAudioMix.inputParameters = [NSArray arrayWithObject:exportAudioMixInputParameters];


/

exportSession.outputURL = [NSURL fileURLWithPath:trimmedAudioFilePath];

exportSession.outputFileType = AVFileTypeAppleM4A;

exportSession.timeRange = exportTimeRange;

exportSession.audioMix = exportAudioMix;


/

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

[exportSession exportAsynchronouslyWithCompletionHandler:^{

dispatch_semaphore_signal(semaphore);

}];

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);


if (AVAssetExportSessionStatusCompleted == exportSession.status) {

NSLog(@"AVAssetExportSessionStatusCompleted");

return trimmedAudioFilePath;

} else if (AVAssetExportSessionStatusFailed == exportSession.status) {

/

/

/

NSLog(@"AVAssetExportSessionStatusFailed %@", exportSession.error.localizedDescription);

} else {

NSLog(@"Export Session Status: %d", exportSession.status);

}

return nil;



After that I add some filter like this:


- (void)startPlayingWithComplete:(void(^)())comlpeteHandler {

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error: nil];

/

engine = [[AVAudioEngine alloc] init];

playerNode = [[AVAudioPlayerNode alloc] init];

[engine attachNode:playerNode];


if ([[NSFileManager defaultManager] fileExistsAtPath:[SSTalkingManager stringPathFile]]) {

AVAudioFile *file = [[AVAudioFile alloc] initForReading:[SSTalkingManager urlVoiceFile] error:nil];

[engine connect:playerNode to:engine.mainMixerNode format:file.processingFormat];

AVAudioFrameCount capacity= (AVAudioFrameCount)file.length;

AVAudioPCMBuffer *buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:file.processingFormat frameCapacity:capacity];

[file readIntoBuffer:buffer error:nil];

AVAudioUnitTimePitch *timePitch = [[AVAudioUnitTimePitch alloc] init];

timePitch.pitch = _pitch;

timePitch.rate = _rate;

[engine attachNode:timePitch];

[engine connect:playerNode to:timePitch format:nil];

[engine connect:timePitch to:engine.outputNode format:nil];

[playerNode scheduleFile:file atTime:nil completionHandler:comlpeteHandler];

NSError * err;

[engine startAndReturnError:&err]; //<--------- This I have a crash. "Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -10868'"

[playerNode play];

}

}



But, if I trim .wav file in Mac and upload to my app in bundle resources then all are OK.


Could you help me?

What I should do in short: I should record voice when user speaks after that I should add some effects to it and then I shoud play effected sound.



Best regards, Andrei.

I am not an expert in AVAudioEngine (still learning) but an observation based on your comment regarding trimming .wav file. In your code you use AVAssetExportSession to export an m4a audio file. If it works when you upload a .wav file from your Mac; then maybe it is the different audio encoding that is causing the problem?

The -10868 error is kAudioUnitErr_FormatNotSupported. Since you have a file that works and a file that doesn't (the one from your Mac and the one exported via AVAssetExportSession), use afinfo and dump the file info for both to see what (if any) the difference are - next I'd dump info from the fileFormat and processingFormat for each case. Should all be the same right since the initForReading method states that it will opens the file for reading using the standard format (deinterleaved floating point) which is the format that the engine should use.


So long answer shortened, you should be able to create a test case where your short piece of player code works once (good file) but then fails the second time (bad file) and it will be obvious what the failure is or you'll have a great bug report you can submit.

Hi, I just noticed that I'm getting a lot of crashes on my app (crashes captured by App Store Connect) when some users (it happens randomly and I wasn't able to replicate) are trying to leave comments into a TextView using AVAudioEngine. I managed to download the crash log from AppStore and I will post it bellow.

Date/Time:           2022-02-25 15:34:02.4994 +0000
Launch Time:         2022-02-25 15:23:54.4546 +0000
OS Version:          iPhone OS 15.3.1 (19D52)
Release Type:        User
Baseband Version:    2.23.02
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                	0x1809510fc __exceptionPreprocess + 220 (NSException.m:200)
1   libobjc.A.dylib               	0x1991a1d64 objc_exception_throw + 60 (objc-exception.mm:565)
2   CoreFoundation                	0x180a275c0 +[NSException raise:format:arguments:] + 100 (NSException.m:147)
3   AVFAudio                      	0x1f3a7961c AVAE_RaiseException(NSString*, ...) + 60 (AVAEInternal.h:69)
4   AVFAudio                      	0x1f3ae5b4c AUGraphNodeBaseV3::CreateRecordingTap(unsigned long, unsigned int, AVAudioFormat*, void (AVAudioPCMBuffer*, AVAudioTime*) block_pointer) + 776 (AVAEInternal.h:77)
5   AVFAudio                      	0x1f3acbf14 AVAudioEngineGraph::InstallTapOnNode(AVAudioNode*, unsigned long, unsigned int, AVAudioFormat*, void (AVAudioPCMBuffer*, AVAudioTime*) block_pointer) + 988 (AVAudioEngineGraph.mm:2029)
6   AVFAudio                      	0x1f3b4f7f8 AVAudioEngineImpl::InstallTapOnNode(AVAudioNode*, unsigned long, unsigned int, AVAudioFormat*, void (AVAudioPCMBuffer*, AVAudioTime*) block_pointer) + 300 (AVAudioEngine.mm:1337)
7   AVFAudio                      	0x1f3b32918 -[AVAudioNode installTapOnBus:bufferSize:format:block:] + 572 (AVAudioNode.mm:185)
8                         	                 0x100a472b4 InspectionCommentsVC.startRecording() + 1608 (InspectionCommentsVC.swift:275)
9                         	                 0x100a48120 specialized InspectionCommentsVC.startStopMicrophoneBtn(_:) + 256 (InspectionCommentsVC.swift:195)
10                        	                 0x100a468bc startStopMicrophoneBtn + 4 (<compiler-generated>:0)
11                        	                 0x100a468bc @objc InspectionCommentsVC.startStopMicrophoneBtn(_:) + 48
12  UIKitCore                     	0x183229a98 -[UIApplication sendAction:to:from:forEvent:] + 100 (UIApplication.m:5361)
13  UIKitCore                     	0x183355db8 -[UIControl sendAction:to:forEvent:] + 128 (UIControl.m:871)
14  UIKitCore                     	0x1830d0f90 -[UIControl _sendActionsForEvents:withEvent:] + 352 (UIControl.m:942)
15  UIKitCore                     	0x18316d864 -[UIButton _sendActionsForEvents:withEvent:] + 160 (UIButton.m:4142)
16  UIKitCore                     	0x183400b40 -[UIControl touchesEnded:withEvent:] + 536 (UIControl.m:637)
17  UIKitCore                     	0x182ed358c -[UIWindow _sendTouchesForEvent:] + 980 (UIWindow.m:2974)
18  UIKitCore                     	0x182f04f48 -[UIWindow sendEvent:] + 4456 (UIWindow.m:3274)
19  UIKitCore                     	0x1830b4e34 -[UIApplication sendEvent:] + 828 (UIApplication.m:11877)
20  UIKitCore                     	0x182ed8140 __dispatchPreprocessedEventFromEventQueue + 7904 (UIEventDispatcher.m:2290)
21  UIKitCore                     	0x182eccf2c __processEventQueue + 6760 (UIEventDispatcher.m:2597)
22  UIKitCore                     	0x183d13d54 updateCycleEntry + 176 (UIEventDispatcher.m:102)
23  UIKitCore                     	0x18353eb44 _UIUpdateSequenceRun + 84 (_UIUpdateSequence.mm:112)
24  UIKitCore                     	0x183bbb84c schedulerStepScheduledMainSection + 144 (_UIUpdateCycleScheduler.m:1174)
25  UIKitCore                     	0x183bbae3c runloopSourceCallback + 60 (_UIUpdateCycleScheduler.m:1262)
26  CoreFoundation                	0x1809730d0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1972)
27  CoreFoundation                	0x180983d90 __CFRunLoopDoSource0 + 208 (CFRunLoop.c:2016)
28  CoreFoundation                	0x1808be098 __CFRunLoopDoSources0 + 268 (CFRunLoop.c:2053)
29  CoreFoundation                	0x1808c38a4 __CFRunLoopRun + 820 (CFRunLoop.c:2951)
30  CoreFoundation                	0x1808d7468 CFRunLoopRunSpecific + 600 (CFRunLoop.c:3268)
31  GraphicsServices              	0x19c47b38c GSEventRunModal + 164 (GSEvent.c:2200)
32  UIKitCore                     	0x18327a5d0 -[UIApplication _run] + 1100 (UIApplication.m:3493)
33  UIKitCore                     	0x182ff8f74 UIApplicationMain + 364 (UIApplication.m:5047)

Thanks for reading this !

Kind regards, Flo

  • Under Organizer -> Crashes section in xCode, the log tells me that the error was thrown from mystartRecording() function. I will also post bellow the code for it and maybe someone with more experience can help me to identify what I'm doing wrong and why AVAudioEngine is crashing.

    func startRecording() {           startStopRecordBtn.setImage(UIImage(#imageLiteral(resourceName: "microphone_off")), for: .normal)     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) { (buffer, when) in       self.recognitionRequest?.append(buffer)     }           audioEngine.prepare()           do {       try audioEngine.start()     } catch {       showAlertWithTitle(message: Constants.error)     }   }
Add a Comment