ios - 使用AVAudioRecorder在后台录制语音

标签 ios background avaudiorecorder

我正在尝试使用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.");
    }            
}

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

最佳答案

尝试这个,

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

}

关于ios - 使用AVAudioRecorder在后台录制语音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264576/

相关文章:

ios - viewDidLoad 在 iOS 8 和 iOS 7 中的调用方式不同?

css - 背景图像在 IE 中不显示,我不知道为什么

javascript - 如何使背景图像响应并覆盖所有区域

iphone - 如何从 iOS AVAudioRecorder 获取正确比例的分贝读数?

ios - 如何在 MacOS Catalyst 应用程序中获取触控板/鼠标滚轮滚动事件?

ios - 执行注销segue

ios - Web 请求后调用时 UIButton 不更新

android - 如何设置ActionBar背景

ios7 - 使用 iOS 7 在 iPhone 5s 上写入/dev/null 时,AVAudioRecorder 停止工作

ios - AVAudioRecorder 丢失最后几秒