我试图克服这个问题一段时间。我正在尝试录制声音,但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 <AVAudioSessionDelegate>) 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 <AVAudioRecorderDelegate>) self;
[_recorder prepareToRecord];
//Start the actual Recording
[_recorder record];
}
请问任何想法?
答案 0 :(得分:4)
好的,所以我花了很长时间才发现问题的答案如下:我发布的代码很好,但实际工作后需要在屏幕锁定后在后台运行。为此,需要在应用程序的plist文件中添加一个UIBackgroundModes数组,并添加“audio”作为其对象之一。这告诉系统让应用程序在后台运行音频。
这是not-so-easy to find documentation。不幸的是,苹果没有在他们声称某些类别在后台工作的音频会话类别的文档中指定。无论如何,希望这个答案可以用于有类似问题的其他人......
答案 1 :(得分:0)
在完成录制之前,如何禁用屏幕锁定?
[UIApplication sharedApplication].idleTimerDisabled = YES;
// Do recording here
[UIApplication sharedApplication].idleTimerDisabled = NO;
完成后不要忘记重新启用屏幕锁定!
答案 2 :(得分:0)
您可能需要考虑将类别 AVAudioSessionCategoryRecord 设置为 AudioSession