屏幕被锁定时,AVAudioRecorder不会录制

我试图克服这个问题一段时间。 我正在尝试录制声音,但AVAudioRecorder在屏幕锁定时不会录制。 一旦屏幕解锁,它会继续记录,但屏幕锁定时录制的音频将永久丢失。 我发现我所做的事情并没有错:

-(void) startRecording { // Begin the recording session. _session = [AVAudioSession sharedInstance]; NSError *setCategoryError = nil; NSError *startRecordError; [_session setActive:YES error:&startRecordError]; [self GKLog:[NSString stringWithFormat:@"recorder session error? :%@", startRecordError]]; [_session setCategory: AVAudioSessionCategoryRecord error: &setCategoryError]; if (setCategoryError) { NSLog(@"some error");} //set me as delegate _session.delegate=(id ) self; NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init]; [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey]; [recordSetting setValue :[NSNumber numberWithInt:8] forKey:AVEncoderBitRateKey]; [recordSetting setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey]; [recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey]; if (!self.currentPath) { NSLog(@"can't record, no path set!"); return; } NSError *error; NSURL *url=[NSURL fileURLWithPath:self.currentPath]; //Setup the recorder to use this file and record to it. _recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&error]; [self GKLog:[NSString stringWithFormat:@" recorder:%@",_recorder]]; _recorder.delegate=(id ) self; [_recorder prepareToRecord]; //Start the actual Recording [_recorder record]; } 

请问有什么想法吗?

好吧,所以我花了很长时间才发现问题的答案如下:我发布的代码很好,但实际工作后需要在屏幕锁定后在后台工作。 为此,需要在应用程序的plist文件中添加一个UIBackgroundModes数组,并添加“audio”作为其对象之一。 这告诉系统让应用程序在后台运行音频。

这是不太容易找到的文档 。 不幸的是,苹果没有在他们声称某些类别在后台工作的音频会话类别的文档中指定。 无论如何,希望这个答案可以用于有类似问题的其他人…

您可能需要考虑将类别设置为AVAudioSessionCategoryRecordAudioSession

在完成录制之前禁用屏幕锁定怎么样?

 [UIApplication sharedApplication].idleTimerDisabled = YES; // Do recording here [UIApplication sharedApplication].idleTimerDisabled = NO; 

完成后别忘了重新启用屏幕锁定!