audio会话中断结束后,AVAudioRecorder不能在后台录音

我在我的应用程序录制audio,无论是在前景和背景。 我也处理AVAudioSessionInterruptionNotification中断开始时停止录音,当它结束时再次开始。 虽然在前台它如预期的那样工作,当应用程序在后台录制时,我收到一个电话,它不会在通话结束后再次开始录音。 我的代码如下:

- (void)p_handleAudioSessionInterruptionNotification:(NSNotification *)notification { NSUInteger interruptionType = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue]; if (interruptionType == AVAudioSessionInterruptionTypeBegan) { if (self.isRecording && !self.interruptedWhileRecording) { [self.recorder stop]; self.interruptedWhileRecording = YES; return; } } if (interruptionType == AVAudioSessionInterruptionTypeEnded) { if (self.interruptedWhileRecording) { NSError *error = nil; [[AVAudioSession sharedInstance] setActive:YES error:&error]; NSDictionary *settings = @{ AVEncoderAudioQualityKey: @(AVAudioQualityMax), AVSampleRateKey: @8000, AVFormatIDKey: @(kAudioFormatLinearPCM), AVNumberOfChannelsKey: @1, AVLinearPCMBitDepthKey: @16, AVLinearPCMIsBigEndianKey: @NO, AVLinearPCMIsFloatKey: @NO }; _recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:nil]; [self.recorder record]; self.interruptedWhileRecording = NO; return; } } } 

请注意,fileURL指向NSDocumentDirectory子目录中的新caf文件。 后台模式audio已configuration。 我也尝试过voip,玩沉默,都没有成功。

AVAudioSessionInterruptionTypeEnded块中的NSError是一个OSStatus错误560557684,我没有find如何解决。

任何帮助将非常感激。

错误560557684是AVAudioSessionErrorCodeCannotInterruptOthers 。 当您的后台应用程序尝试激活不与其他audio会话混合的audio会话时,会发生这种情况。 后台应用程序无法启动不与前台应用程序的audio会话混合的audio会话,因为这会中断用户当前正在使用的应用程序的audio。

要解决此问题,请确保将会话类别设置为可混合的类别,例如AVAudioSessionCategoryPlayback 。 另外一定要设置类别选项AVAudioSessionCategoryOptionMixWithOthers (必需)和AVAudioSessionCategoryOptionDuckOthers (可选)。 例如:

 // background audio *must* mix with other sessions (or setActive will fail) NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDuckOthers error:&sessionError]; if (sessionError) { NSLog(@"ERROR: setCategory %@", [sessionError localizedDescription]); } 

错误代码560557684实际上是一个32位整数的4个ASCII字符'!int'。 错误代码列在AVAudioSession.h文件中(另请参阅AVAudioSession ):

  @enum AVAudioSession error codes @abstract These are the error codes returned from the AVAudioSession API. ... @constant AVAudioSessionErrorCodeCannotInterruptOthers The app's audio session is non-mixable and trying to go active while in the background. This is allowed only when the app is the NowPlaying app. typedef NS_ENUM(NSInteger, AVAudioSessionErrorCode) { ... AVAudioSessionErrorCodeCannotInterruptOthers = '!int', /* 0x21696E74, 560557684 */ ... 

我添加了以下内容

 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 

在configurationAVAudioSession之前,它工作。 仍然不知道可能出现的错误。