Ios 设置AVCaptureConnection视频方向时滞后

Ios 设置AVCaptureConnection视频方向时滞后,ios,objective-c,xcode,avfoundation,avcapturesession,Ios,Objective C,Xcode,Avfoundation,Avcapturesession,该问题使用AVFoundation设置相机,其输出显示在AVCaptureVideoPreviewLayer中,并作为像素缓冲区处理。为了通过-processSampleBuffer:方法处理像素缓冲区,必须以正确的方向提供它,这取决于设备方向 据我所知,这可以通过在-captureOutput:didOutputSampleBuffer:fromConnection:中访问原始像素值,或者通过在相应的AVCaptureConnection上设置videoOrientation属性来实现,确保在

该问题使用
AVFoundation
设置相机,其输出显示在
AVCaptureVideoPreviewLayer
中,并作为像素缓冲区处理。为了通过
-processSampleBuffer:
方法处理像素缓冲区,必须以正确的方向提供它,这取决于设备方向

据我所知,这可以通过在
-captureOutput:didOutputSampleBuffer:fromConnection:
中访问原始像素值,或者通过在相应的
AVCaptureConnection
上设置
videoOrientation
属性来实现,确保在所需方向提供像素缓冲区。设置概要如下所示:

- (void)setupCamera
{
    AVCaptureSession *session = [AVCaptureSession new];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:nil];
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    [session addInput:deviceInput];

    dispatch_queue_t videoOutputQueue = dispatch_queue_create("com.MyApp.videoQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_set_target_queue(videoOutputQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));

    AVCaptureVideoDataOutput *videoOutput = [AVCaptureVideoDataOutput new];
    videoOutput.alwaysDiscardsLateVideoFrames = YES;
    [videoOutput setSampleBufferDelegate:self queue:videoOutputQueue];
    [session addOutput:videoOutput];

    // more setup
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    connection.videoOrientation = [self getCurrentOrientation]; // setting this to a new value causes the preview layer to freeze momentarily
    [self processSampleBuffer:sampleBuffer]; // some arbitrary image processing method
}

就像素缓冲区的方向而言,这与预期的一样有效,但是,每当设备旋转到新的方向时,会提供
连接。videoOrientation
一个新值,预览层会冻结几分之一秒。阻止委托方法的线程(例如,通过添加睡眠)不会冻结预览层,因此这不是问题所在。非常感谢您对解决方案的任何帮助

你解决了这个问题吗?有类似的问题。。但我相信在改变方向时相机可能会重新启动。问题是相机确实会重新启动。我发现要解决这个问题,我需要在整个视图生命周期的最开始,甚至在向用户显示AVPreviewLayer之前,设置AVCaptureConnection的方向。我建议在这种情况下展示一个旋转的“加载”轮。在预览层上显示视频输出后,设置延迟似乎是最糟糕的。如果你很早就这样做,就不会有太大的滞后。