使用AVAudioRecorder在后台录制语音

时间:2013-03-07 06:28:22

标签: ios background avaudiorecorder

我正在尝试使用AVAudioRecorder在后​​台录制用户语音,但每次调用NO方法时我都会recordForDuration。我将“音频”添加到UIBackgroundModes,但这没有帮助。 顺便说一句,Everything在前景中完美无缺。我正在使用此代码初始化AVAudioRecorder

NSError* error;
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error])
{
    NSLog(@"Error while setting audio session category. Code - %d, description - \"%@\".", [error code], [error localizedDescription]);
    return;
}

NSURL* outputFileURL = [VKMFileSystemHelper uniqueFileInPath:[[VKMFileSystemHelper subdirectoryInsideLibrary:DIR_AUDIO] path] withExtension:@"m4a"];

NSDictionary* recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                    [NSNumber numberWithInt:AVAudioQualityMin]   , AVEncoderAudioQualityKey,
                                    [NSNumber numberWithInt:16]                  , AVEncoderBitRateKey,
                                    [NSNumber numberWithInt:1]                   , AVNumberOfChannelsKey,
                                    [NSNumber numberWithFloat:12000.0]           , AVSampleRateKey,
                                    nil];

_recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSettings error:&error];
[_recorder setDelegate:self];

if (error)
{
    NSLog(@"Error occured during audio recorder initialization. Error code - %d, description - \"%@\".", [error code], [error localizedDescription]);
}
else
{
    NSLog(@"Start recording.");
    if ([_recorder recordForDuration:[shedule execLength]])
    {
        NSLog(@"Record started.");
    }
    else
    {
        NSLog(@"Record failed.");
    }            
}

如何从背景录制麦克风?这可能吗?

1 个答案:

答案 0 :(得分:3)

试试这个,

        ***Appdelegate.m***

- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
    NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
    [application endBackgroundTask:task];
    task=UIBackgroundTaskInvalid;
}];

}