Change camera capture device while recording a video

两盒软妹~` 提交于 2019-11-29 00:37:51
hatebyte

Yes, you can. There are just a few of things you need to cater to.

  1. Need to be using AVCaptureVideoDataOutput and its delegate for recording.
  2. Make sure you remove the previous deviceInput before adding the new deviceInput.
  3. You must remove and recreate the AVCaptureVideoDataOutput as well.

I am using these two functions for it right now and it works while the session is running.

- (void)configureVideoWithDevice:(AVCaptureDevice *)camera {

    [_session beginConfiguration];
    [_session removeInput:_videoInputDevice];
    _videoInputDevice = nil;

    _videoInputDevice = [AVCaptureDeviceInput deviceInputWithDevice:camera error:nil];
    if ([_session canAddInput:_videoInputDevice]) {
        [_session addInput:_videoInputDevice];
    }

    [_session removeOutput:_videoDataOutput];
    _videoDataOutput = nil;

    _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
    [_videoDataOutput setSampleBufferDelegate:self queue:_outputQueueVideo];
    NSDictionary* setcapSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey, nil];

    _videoDataOutput.videoSettings = setcapSettings;
    [_session addOutput:_videoDataOutput];
    _videoConnection = [_videoDataOutput connectionWithMediaType:AVMediaTypeVideo];

    if([_videoConnection isVideoOrientationSupported]) {
        [_videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
    }  

    [_session commitConfiguration];
}

- (void)configureAudioWithDevice:(AVCaptureDevice *)microphone {
    [_session beginConfiguration];
    _audioInputDevice = [AVCaptureDeviceInput deviceInputWithDevice:microphone error:nil];
    if ([_session canAddInput:_audioInputDevice]) {
        [_session addInput:_audioInputDevice];
    }

    [_session removeOutput:_audioDataOutput];
    _audioDataOutput = nil;

    _audioDataOutput = [[AVCaptureAudioDataOutput alloc] init];
    [_audioDataOutput setSampleBufferDelegate:self queue:_outputQueueAudio];
    [_session addOutput:_audioDataOutput];
    _audioConnection = [_audioDataOutput connectionWithMediaType:AVMediaTypeAudio];

    [_session commitConfiguration];
}

You can't change the captureDevice mid-session. And you can only have one capture session running at a time. You could end the current session and create a new one. There will be a slight lag (maybe a second or two depending on your cpu load).

I wish Apple would allow multiple sessions or at least multiple devices per session... but they do not... yet.

have you considered having multiple sessions and then afterwards processing the video files to join them together into one?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!