2012-06-17 36 views
13

我想在兩個UIView中彼此相鄰顯示iPad2的前置攝像頭和後置攝像頭的流。 要流一個設備的所述圖像I使用以下代碼運行多個AVCaptureSessions或添加多個輸入

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添加到會話中,但似乎目前最多隻支持一個輸入。

任何有用的想法如何從兩個相機流?

+0

可能的重複[如何讓自動對焦在第二個AVCaptureSession中工作而不重新創建會話?](http://stackoverflow.com/questions/5427561/how-can-i-get-autofocus-to-work -in-a-second-avcapturesession-without-recreating) –

回答

13

可以從MacOS X上你手動AVCaptureConnection對象必須設置多個視頻設備得到CMSampleBufferRef秒。例如,假設你有這些對象:

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 sample project,以結合多個視頻設備的實時預覽。

+0

謝謝你爲我工作了一個補充。我也必須這樣做: [session addInputWithNoConnections:videoInput1]; [session addInputWithNoConnections:videoInput2]; –

+6

無法在iOS 10上工作 - 將第二個輸入添加到會話失敗:由於未捕獲異常'NSInvalidArgumentException'而終止應用,原因:'*** - [AVCaptureSession addInputWithNoConnections:]當前不支持多個音頻/視頻AVCaptureInputs –