在Swift中,改编了AVCaptureVideoDataOutputSampleBufferDelegate,但是captureOutput永远不会被调用

时间:2015-05-07 09:56:19

标签: ios swift video-capture capture avcapturesession

我试图从相机捕获视频帧并实时显示UIImageView上的图像泛滥。 我尝试为AVCaptureVideoDataOutputSampleBufferDelegate调整viewcontroller。 我还实施了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()工作正常....

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

1 个答案:

答案 0 :(得分:6)

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