2013-03-07 135 views
1

我试图用AVAudioRecorder在后台录制用户声音,但每次我在获取NO的同时调用recordForDuration方法。我添加了“音频”到UIBackgroundModes但这没有帮助。顺便说一句,一切工作在前景完美。使用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."); 
    }    
} 

我怎样才能从后台麦克风录音:我使用这个代码初始化AVAudioRecorder?这可能吗?

回答

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; 
}]; 

} 
+0

严格地说,它只是允许在运行10分钟。有什么办法让它整天运行吗? – Jacky 2013-07-06 22:03:33

相关问题