2017-09-23 81 views
0

所以我有這個問題,我試圖在Xcode中創建一個自定義相機,但出於某種原因,我無法得到它,因此它被設置爲使用前置相機。無論我在代碼中改變了什麼,它似乎只使用後置攝像頭,我希望有人可能會慷慨地快速查看下面的代碼,看看是否有某些我丟失的或我去過的地方錯誤。任何幫助將非常感激,謝謝你的時間。xcode,Swift 3自定義相機

func SelectInputDevice() { 

let devices = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, 
       mediaType: AVMediaTypeVideo, position: .front) 
if devices?.position == AVCaptureDevicePosition.front { 

print(devices?.position) 
frontCamera = devices 

} 

currentCameraDevice = frontCamera 
do { 

    let captureDeviceInput = try AVCaptureDeviceInput(device: currentCameraDevice) 
    captureSession.addInput(captureDeviceInput) 

} catch { 

    print(error.localizedDescription) 

    } 

} 

這是frontCamera和currentCameraDevice是AVCaptureDevice的地方。

回答

1

似乎有幾件事情從你的代碼丟失:

1)爲了改變,你需要通過添加新的設備,並與session.commitConfiguration()結束之前調用session.beginConfiguration()重新配置會話的輸入設備。此外,所有更改都應在後臺隊列上進行(希望您已爲該會話創建),以便在配置會話時不會阻止UI。

2)代碼會更安全地檢查會話,它允許新設備添加之前session.canAddInput(captureDeviceInput) +刪除以前的設備(後置攝像頭),因爲前+後配置是不允許的。

3)也會更清潔,以檢查您的設備有一個工作前攝像頭(可能會被打破)之前,以防止任何崩潰。

改變捕獲設備的前置攝像頭的完整代碼如下所示:

func switchCameraToFront() { 

    //session & sessionQueue are references to the capture session and its dispatch queue 
    sessionQueue.async { [unowned self] in 

     let currentVideoInput = self.videoDeviceInput //ref to current videoInput as setup in initial session config 

     let preferredPosition: AVCaptureDevicePosition = .front 
     let preferredDeviceType: AVCaptureDeviceType = .builtInWideAngleCamera 

     let devices = self.videoDeviceDiscoverySession.devices! 
     var newVideoDevice: AVCaptureDevice? = nil 

     // First, look for a device with both the preferred position and device type. Otherwise, look for a device with only the preferred position. 
     if let device = devices.filter({ $0.position == preferredPosition && $0.deviceType == preferredDeviceType }).first { 
      newVideoDevice = device 
     } 
     else if let device = devices.filter({ $0.position == preferredPosition }).first { 
      newVideoDevice = device 
     } 

     if let videoDevice = newVideoDevice { 
      do { 
       let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) 

       self.session.beginConfiguration() 

       // Remove the existing device input first, since using the front and back camera simultaneously is not supported. 
       self.session.removeInput(currentVideoInput) 

       if self.session.canAddInput(videoDeviceInput) {            

        self.session.addInput(videoDeviceInput) 
        self.videoDeviceInput = videoDeviceInput 
       } 
       else { 
        //fallback to current device 
        self.session.addInput(self.videoDeviceInput); 
       } 
       self.session.commitConfiguration() 
      } 
      catch { 

      } 
     } 
    } 
} 
+0

意想不到的回答感謝您的時間! – imjonu