我在Swift中使用OpenGLES进行照片预览而不是使用图层,因为我想在输出上放置滤镜。我正在使用我在objc.io objc.io camera capture tutorial
上找到的代码我收到此错误 -
BSXPCMessage收到错误消息:连接中断
并且预览不会运行 - 空白屏幕
代码如下
import UIKit
import AVFoundation
import GLKit
import OpenGLES
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
let captureSession = AVCaptureSession()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var captureDevice : AVCaptureDevice?
let devices = AVCaptureDevice.devices()
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
if(device.position == AVCaptureDevicePosition.Front) {
captureDevice = device as? AVCaptureDevice
}
}
}
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
captureSession.startRunning()
let videoOutput : AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL))
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
}
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
let viewFrame : CGRect = self.view.frame
let glContext = EAGLContext(API: .OpenGLES2)
let glView = GLKView(frame: viewFrame, context: glContext)
let ciContext = CIContext(EAGLContext: glContext)
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let image = CIImage(CVPixelBuffer: pixelBuffer)
if glContext != EAGLContext.currentContext() {
EAGLContext.setCurrentContext(glContext)
}
glView.bindDrawable()
ciContext.drawImage(image, inRect:image.extent(), fromRect: image.extent())
glView.display()
}