访问Swift 4中的前置摄像头

时间:2017-10-25 02:20:05

标签: swift camera avfoundation

我在相机应用程序中有这个

session.sessionPreset = AVCaptureSession.Preset.high
camera = AVCaptureDevice.default(for: AVMediaType.video)

    do {
        let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!)
        cameraCaptureOutput = AVCapturePhotoOutput()

        session.addInput(cameraCaptureInput)
        session.addOutput(cameraCaptureOutput!)

    } catch {
        print(error.localizedDescription)
    }

如何访问前置摄像头?

1 个答案:

答案 0 :(得分:6)

您可以通过这种方式设置AVCaptureDevice。只需将默认position设置为front相机即可。

        var defaultVideoDevice: AVCaptureDevice?

        // Choose the back dual camera if available, otherwise default to a wide angle camera.
        if let dualCameraDevice = AVCaptureDevice.default(.builtInDualCamera, for: AVMediaType.video, position: .back) {
            defaultVideoDevice = dualCameraDevice
        }

        else if let backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) {
            defaultVideoDevice = backCameraDevice
        }

        else if let frontCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front) {
            defaultVideoDevice = frontCameraDevice
        }

        let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVideoDevice!)