如何在Swift中获得前置摄像头?

时间:2015-03-19 21:48:59

标签: ios iphone swift

我正在尝试使用实时视图获取前置摄像头。我可以使用以下方式获得后置摄像头:

var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

但我似乎无法找到如何获得前置摄像头。如何更改上面的代码才能使用前置摄像头?

8 个答案:

答案 0 :(得分:21)

这是我的一个项目的工作示例,以获得前置摄像头。这是客观的,但经过验证可以很容易地转换成swift。

NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *captureDevice = nil;

for (AVCaptureDevice *device in videoDevices){

    if (device.position == AVCaptureDevicePositionFront){

        captureDevice = device;
        break;
    }
}

在Swift 3.2 +中:

if let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
    var captureDevice: AVCaptureDevice
    for device in videoDevices {
        if let device = device as? AVCaptureDevice {
            if device.position == AVCaptureDevicePosition.front {
                captureDevice = device
                break
            }
        }
    }
}

答案 1 :(得分:9)

guard let device = AVCaptureDevice.devices().filter({ $0.position == .Front })
    .first as? AVCaptureDevice else {
        fatalError("No front facing camera found")
}

如果您正在寻找更短的解决方案,尽管.filter后跟.first不是最有效的

答案 2 :(得分:9)

在iOS 10.0及更高版本中,您无需遍历AVCaptureDevicedevices(或devicesWithMediaType)以按位置查找相机。 (事实上​​,这两种API在iOS 10中都已弃用,并且不会在iPhone 7 Plus,iPhone 8 Plus或iPhone X上返回全套可用设备。)

如果您只需要根据简单的特征找到单个设备(例如可以拍摄视频的前置摄像头),只需使用AVCaptureDevicedefaultDevice(withDeviceType:mediaType:position:)。例如:

guard let device = AVCaptureDevice.defaultDevice(
    withDeviceType: .builtInWideAngleCamera,
    mediaType: AVMediaTypeVideo,
    position: .front)
    else { fatalError("no front camera. but don't all iOS 10 devices have them?")

// then use the device: captureSession.addInput(device) or whatever

对于大多数用例来说,确实是这样。

还有AVCaptureDeviceDiscoverySession作为迭代devices数组的旧方法的替代品。但是,您可以使用新的defaultDevice(withDeviceType:mediaType:position:)方法找到您通常遍历devices数组的大部分内容,因此您可以使用它并编写更少的代码。

AVCaptureDeviceDiscoverySession值得使用的情况是不太常见,更复杂的情况:假设您想要找到支持特定帧速率的所有设备,或者使用键值观察来查看何时设置可用的设备更改。

顺便说一句,Apple也有a guide到iOS 10 / Swift 3照片捕获系统和一些sample code,它们都显示了这些API的最新实践。

答案 3 :(得分:4)

Swift 4.1,iOS 10+和 Xcode 9.3 取代

if let cameraID = AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front)?.localizedName {
       //cameraID = "Front Camera"
}

使用 AVCaptureDevice.DiscoverySession 实施

if let cameraID = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.front).devices.first?.localizedName{
        //cameraID = "Front Camera"
} 

答案 4 :(得分:2)

延迟是:

guard let device = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: .video, position: .front) else {
    return
}

答案 5 :(得分:1)

基于mbuff24提供的解决方案。 数组方法包括.first(where :)除了.filter()

guard let frontCamera = AVCaptureDevice.devices().first(where: { ($0 as AnyObject).position == .front }) as? AVCaptureDevice else {
            fatalError("No front facing camera found")
            }

答案 6 :(得分:0)

import AVFoundation
import Foundation


@IBOutlet weak var imageView: UIImageView!
    let captureSession = AVCaptureSession()
    let stillImageOutput = AVCaptureStillImageOutput()
    var previewLayer : AVCaptureVideoPreviewLayer?
    var captureDevice : AVCaptureDevice?
    var Arrdata:[Studentdata] = []
 override func viewDidLoad() {
        super.viewDidLoad()
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
            if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice]
            {
                for device in devices
                {
                    if (device.hasMediaType(AVMediaTypeVideo))
                    {
                        if(device.position == AVCaptureDevicePosition.front)
                        {
                            captureDevice = device
                            if captureDevice != nil
                            {
                                print("Capture device found")
                                beginSession()
                            }
                        }
                    }
                }
            }


    }

func beginSession()
    {
        do
        {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            if captureSession.canAddOutput(stillImageOutput)
            {
                captureSession.addOutput(stillImageOutput)
            }
        }
        catch
        {
            print("error: \(error.localizedDescription)")
        }
        guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else
        {
            print("no preview layer")
            return
        }
        self.view.layer.addSublayer(previewLayer)
        previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()
        self.view.addSubview(imageView)
    }

答案 7 :(得分:0)

for (const theElement of filtered) {
  Object.assign(theElement, toMerge[theElement.key]);
}

console.log(filtered)