使用 AVFoundation 在 UIView 中显示相机提要

Show camera feed in UIView using AVFoundation

我正在尝试在 UIView 中显示相机的提要。稍后我需要能够分析视频帧,所以我需要使用 AVFoundation 来执行此操作,据我所知。

我目前拥有的:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var camView: UIView!

    var captureSession:AVCaptureSession?
    var videoPreviewLayer:AVCaptureVideoPreviewLayer?
    var videoCaptureDevice: AVCaptureDevice?
    var input: AnyObject?

    override func viewDidLoad() {
        super.viewDidLoad()

        videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            input = try AVCaptureDeviceInput(device: videoCaptureDevice)
        } catch {
            print("video device error")
        }
        captureSession = AVCaptureSession()
        captureSession?.addInput(input as! AVCaptureInput)
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        videoPreviewLayer?.frame = camView.layer.bounds
        captureSession?.startRunning()
    }
}

camView 是可见的,但没有显示任何内容。

该应用最初请求使用相机的权限运行,并已获得该权限。

设置断点并检查 captureSessionvideoPreviewLayervideoCaptureDeviceinput 确认它们已全部设置。

camView中没有添加视频预览层。因此,您无法在 camView 中看到相机会话 运行。

添加这一行:

    camView.layer.addSublayer(videoPreviewLayer)