Поддержка фоновой записи видео с использованием AVCaptureSession

Я пытаюсь записывать видео также в фоновом режиме, но в настоящее время мой код записывает видео на переднем плане, когда приложение переходит в фоновый режим.

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error

срабатывает сразу с ошибкой как

     error:Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo=0x176aa180 {NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., NSUnderlyingError=0x1766c0e0 "The operation couldn’t be completed. (OSStatus error -16133.)", NSLocalizedDescription=Recording Stopped}

Я установил следующее значение в моем DemoApp-Info.plist

Required background modes->App plays audio or streams audio/video using AirPlay
Application does not run in background->NO

Ниже мой код

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.captureSession = [[AVCaptureSession alloc] init];
    //CONFIGURE VIDEO RECORING
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    if(self.videoInput){
        [self.captureSession addInput:self.videoInput];
    }
    else{
        NSLog(@"Input Error:%@", error);
    }

    //CONFIGURE AUDIO RECORDING
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    AVCaptureDeviceInput *captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
    if(captureDeviceInput){
        [self.captureSession addInput:captureDeviceInput];
    }

    //CONFIGURE DISPLAY OUTPUT
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    previewLayer.frame = self.view.frame;
    [self.view.layer addSublayer:previewLayer];

    //CONFIGURE FILE OUTPUT
    //HANDLE EVENT IN RECORD START/STOP ACTION AND ALSO IN AVCaptureMovieFileOutput DELEGATE
    self.captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

    if([self.captureSession canAddOutput:self.captureMovieFileOutput]){
        [self.captureSession addOutput:self.captureMovieFileOutput];
    }
}



- (IBAction)btnRecordClicked:(UIBarButtonItem *)sender {

    if([[sender title] isEqualToString:@"Record"]){

        NSError *error = nil;
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [[AVAudioSession sharedInstance] setDelegate:self];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
        NSLog(@"audioSessionError:%@", error);
        [[AVAudioSession sharedInstance] setActive:YES error: nil];
        self.captureSession.usesApplicationAudioSession = YES;
        self.captureSession.automaticallyConfiguresApplicationAudioSession = YES;
        sender.title = @"Stop";
        [self.captureSession startRunning];

        //CREATE FILE
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

        NSString *outputFileName = [[kAppDocDirPath stringByAppendingPathComponent:[dateFormatter stringFromDate:[NSDate date]]] stringByAppendingPathExtension:@"mp4"];
        NSURL *outputFileURL = [[NSURL alloc] initFileURLWithPath:outputFileName];

        [self.captureMovieFileOutput startRecordingToOutputFileURL:outputFileURL recordingDelegate:self];
    }
    else{
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [[AVAudioSession sharedInstance] setDelegate:nil];
        [[AVAudioSession sharedInstance] setActive:NO error: nil];

        sender.title = @"Record";
        [self.captureSession stopRunning];
        [self.captureMovieFileOutput stopRecording];
    }
}
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
    BOOL isSuccess = YES;
    NSLog(@"error:%@", error);
    if(error.code != noErr)
    {
        id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
        if(value)
        {
            isSuccess = [value boolValue];
        }
    }

    if(isSuccess)
    {
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        if([assetsLibrary videoAtPathIsCompatibleWithSavedPhotosAlbum:outputFileURL])
        {
            [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
                if(error){
                    NSLog(@"Error:%@", error);
                }

                //delete temporary file
                NSError *aError = nil;
                [[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:&aError];
            }];

        }
        else{
            NSLog(@"could not saved to photos album.");
        }
    }

}

Ответы на вопрос(0)

Ваш ответ на вопрос