在 Swift 中,改编了 AVCaptureVideoDataOutputSampleBufferDelegate,但从未调用 captureOutput

In Swift, adapted AVCaptureVideoDataOutputSampleBufferDelegate, but captureOutput never getting called

我正在尝试从摄像头捕获视频帧并在 UIImageView 上实时显示大量图像。 我试图为我的 viewcontroller 调整 AVCaptureVideoDataOutputSampleBufferDelegate。 我也实现了 captureOutput,但是 captureOutput 从来没有被调用过。

这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet var cameraView: UIView!

    var selectedImage :UIImage!

    let captureSession = AVCaptureSession()
    var captureDevice : AVCaptureDevice?
    var videoCaptureOutput : AVCaptureVideoDataOutput!

     override func viewDidLoad() {
        super.viewDidLoad()

        captureSession.sessionPreset = AVCaptureSessionPresetLow
        self.captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        if(captureDevice != nil){
            beginSession()
        }
    }


    func beginSession() {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { 
            self.videoCaptureOutput = AVCaptureVideoDataOutput()
            self.videoCaptureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey:kCVPixelFormatType_32BGRA]
            self.videoCaptureOutput.alwaysDiscardsLateVideoFrames = true

            self.captureSession.addOutput(self.videoCaptureOutput)

            var err : NSError? = nil
            self.captureSession.addInput(AVCaptureDeviceInput(device: self.captureDevice, error: &err))
            self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto
            if err != nil {
                println("error: \(err?.localizedDescription)")
            }
            var previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
            previewLayer?.frame = self.cameraView.layer.bounds
            previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            dispatch_async(dispatch_get_main_queue(), { // 2
                // 3
                self.cameraView.layer.addSublayer(previewLayer)
                self.captureSession.startRunning()

            });
        });
    }

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

        println("capture delegation called")

        var imageProcessor = ImageProcessor()
        imageView.image = imageProcessor.imageFromSampleBuffer(sampleBuffer)
    }
}

如您所见,我正在尝试在 imageview 上处理图像并显示实时捕获帧,假设我的 ImageProcessor() 工作正常....

非常感谢任何帮助,谢谢。

您的委托方法未被调用,因为您根本没有将委托设置为 videoCaptureOutput。为此,您必须调用 videoCaptureOutput setSampleBufferDelegate(self ,queue : queue ) 方法,其中队列参数是应在其上调用回调的队列