更换相机iOS后相机帧丢失

时间:2015-08-24 23:42:20

标签: ios avfoundation

成功调用我的方法didOutputSampleBuffer,直到我使用此功能切换摄像机:

func switchCameras() {

    captureSession.beginConfiguration()
    captureSession.sessionPreset = AVCaptureSessionPresetMedium
    var error : NSError? = nil
    for input in captureSession.inputs {
        captureSession.removeInput(input as! AVCaptureInput)
    }
    if currentCamera == "back" {
        currentCamera = "front"

        if captureSession.canAddInput(AVCaptureDeviceInput(device: frontCamera, error: &error)) {
            captureSession.addInput(AVCaptureDeviceInput(device: frontCamera, error: &error))
        } else {
            print(error)
        }
    } else {
        currentCamera = "back"
        if captureSession.canAddInput(AVCaptureDeviceInput(device: backCamera, error: &error)) {
            captureSession.addInput(AVCaptureDeviceInput(device: backCamera, error: &error))
        } else {
        }
    }
    print("chagned")
    captureSession.commitConfiguration()
}

切换后,这种方法有时会丢帧,所以我无法拍照。大约5秒钟后,帧会回来。

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    connection.videoOrientation = AVCaptureVideoOrientation.Portrait

    if capture == true {
        self.capture = false
        var newBuffer = sampleBuffer
            self.capturePicture(newBuffer)


    }
}

如果您需要更多代码,请告诉我。

1 个答案:

答案 0 :(得分:1)

我通过将输出队列更改为DISPATCH_QUEUE_SERIAL来解决此问题。

let output = AVCaptureVideoDataOutput()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as NSString:kCVPixelFormatType_32BGRA]
let queue = dispatch_queue_create("cameraQueue", DISPATCH_QUEUE_SERIAL)
output.setSampleBufferDelegate(self, queue: dispatch_get_main_queue())