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

sef*_*osu 5 video-capture capture ios avcapturesession swift

我正试图从相机捕捉视频帧并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)
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我正在尝试处理图像并显示实时捕捉帧imageview,假设我的ImageProcessor()作品完美....

任何帮助将不胜感激,谢谢.

Zel*_* B. 6

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