2017-03-01 64 views
0

我想構建前置攝像頭,但無法在Swift中構建前置攝像頭,即使我可以構建相機。無法在Swift中使用前置攝像頭

當我只改「回」到「前方」,攝像頭沒有工作......

如何使用前置攝像頭?

var captureSesssion: AVCaptureSession! 
var stillImageOutput: AVCapturePhotoOutput? 
var previewLayer: AVCaptureVideoPreviewLayer? 
var captureDevice : AVCaptureDevice! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    captureSesssion = AVCaptureSession() 
    stillImageOutput = AVCapturePhotoOutput() 

    captureSesssion.sessionPreset = AVCaptureSessionPreset1920x1080 

    captureDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) 
    //When change "front" to "back", camera is built. 

    do { 
     let input = try AVCaptureDeviceInput(device: captureDevice) 

     if (captureSesssion.canAddInput(input)) { 
      captureSesssion.addInput(input) 

      if (captureSesssion.canAddOutput(stillImageOutput)) { 
       captureSesssion.addOutput(stillImageOutput) 
       captureSesssion.startRunning() 

       previewLayer = AVCaptureVideoPreviewLayer(session: captureSesssion) 
       previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect 
       previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait 

       self.view.layer.addSublayer(previewLayer!) 

       previewLayer?.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2) 
       previewLayer?.bounds = self.view.frame 
      } 
     } 
    } 
    catch { 
     print(error) 
    } 
+0

您的測試設備的自拍相機在相機應用程序上工作嗎? – owlswipe

+0

是的,我使用iPhone SE,可以在相機應用程序中使用前置攝像頭。 – bao

回答

3

用於iPhone 7和iPhone 7 Plus的前置攝像頭可以錄製1080p,但在舊款機型上它只能錄製720p。因此,您只需更改會話預設即:

captureSesssion.sessionPreset = AVCaptureSessionPreset1280x720 
+0

謝謝!它確實工作:) – bao

相關問題