为什么切换相机会使我的 AVCaptureSession 停止到 MovieFileOutput?

Why does switching cameras stop my AVCaptureSession to MovieFileOutput?

iOS documentation 表示您可以在会话 运行 时添加和删除输入,例如在前后摄像头之间切换。

但是当我尝试这个时,我的会话停止了。我正在使用 beginConfigurationcommitConfiguration 调用锁定会话,如下所示:

- (void)switchCamera:(UIButton *)sender {

    dispatch_async([self sessionQueue], ^{

        AVCaptureSession *session = self.captureSession;
        [session beginConfiguration];

        AVCaptureInput *currentInput = self.currentCameraIsBack ? self.videoDeviceInputBack : self.videoDeviceInputFront;
        AVCaptureInput *newInput = self.currentCameraIsBack ? self.videoDeviceInputFront : self.videoDeviceInputBack;

        [session removeInput:currentInput];
        [session addInput:newInput];
        self.currentCameraIsBack = !self.currentCameraIsBack;

        [session setSessionPreset:AVCaptureSessionPresetMedium];
        [self setCameraOutputProperties];

        [session commitConfiguration];
    });
}

我正在输出到 AVCaptureMovieFileOutput。我需要做些什么来配置此会话以便它可以切换吗?

(请注意 this question 中的 OP 试图在不删除旧输入的情况下添加新输入,这不是这里的问题)

事实证明,要做到这一点,您需要使用 AVAssetWriter 并使用结果 CMSampleBuffer 自己调用 appendSampleBuffer:,如下所示:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

    if (self.recording && self.videoWriterInput.isReadyForMoreMediaData) {

        [self.videoWriterInput appendSampleBuffer:sampleBuffer];
    }
}