17

我想在两个相邻的 UIView 中显示 iPad2 的前置和后置摄像头的流。要流式传输一台设备的图像,我使用以下代码

AVCaptureDeviceInput *captureInputFront = [AVCaptureDeviceInput deviceInputWithDevice:[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo] error:nil];

AVCaptureSession *session = [[AVCaptureSession alloc] init];
session addInput:captureInputFront];
session setSessionPreset:AVCaptureSessionPresetMedium];
session startRunning];

AVCaptureVideoPreviewLayer *prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
prevLayer.frame = self.view.frame;
[self.view.layer addSublayer:prevLayer];

这适用于任一相机。为了并行显示流,我尝试创建另一个会话,但是一旦建立第二个会话,第一个会话就会冻结。

然后我尝试将两个 AVCaptureDeviceInput 添加到会话中,但目前似乎最多支持一个输入。

任何有用的想法如何从两个摄像机流式传输?

4

1 回答 1

23

在MacOS X可以从多个视频设备获取CMSampleBufferRefs。您必须AVCaptureConnection手动设置对象。例如,假设您有这些对象:

AVCaptureSession *session;
AVCaptureInput *videoInput1;
AVCaptureInput *videoInput2;
AVCaptureVideoDataOutput *videoOutput1;
AVCaptureVideoDataOutput *videoOutput2;

不要这样添加输出:

[session addOutput:videoOutput1];
[session addOutput:videoOutput2];

相反,添加它们并告诉会话不要建立任何连接:

[session addOutputWithNoConnections:videoOutput1];
[session addOutputWithNoConnections:videoOutput2];

然后为每个输入/输出对手动从输入的视频端口连接到输出:

for (AVCaptureInputPort *port in [videoInput1 ports]) {
    if ([[port mediaType] isEqualToString:AVMediaTypeVideo]) {
        AVCaptureConnection* cxn = [AVCaptureConnection
            connectionWithInputPorts:[NSArray arrayWithObject:port]
            output:videoOutput1
        ];
        if ([session canAddConnection:cxn]) {
            [session addConnection:cxn];
        }
        break;
    }
}

最后,确保为两个输出设置样本缓冲区委托:

[videoOutput1 setSampleBufferDelegate:self queue:someDispatchQueue];
[videoOutput2 setSampleBufferDelegate:self queue:someDispatchQueue];

现在您应该能够处理来自两个设备的帧:

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    if (captureOutput == videoOutput1)
    {
        // handle frames from first device
    }
    else if (captureOutput == videoOutput2)
    {
        // handle frames from second device
    }
}

另请参阅AVVideoWall 示例项目,了解组合来自多个视频设备的实时预览的示例。

于 2015-05-12T12:33:18.087 回答