2013-03-07 129 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

相關問題