简体   繁体   中英

Recording voice in background using AVAudioRecorder

I'm trying to record user voice in background using AVAudioRecorder but every time i get NO while calling recordForDuration method. I add "audio" to UIBackgroundModes but this don't help. By the way, Everything works perfect in foreground. I'm initializing AVAudioRecorder using this code:

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.");
    }            
}

How can i record from microphone from background ? Is this possible?

Try this,

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM