connectionWithMediaType

connectionWithMediaType

我尝试使用glkview实现视频供稿,但是当我尝试旋转旋转时,总是从connectionWithMediaType返回nil。

这是我的设置

override public func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    videoFeed = GLKView(frame: self.view.bounds, context: EAGLContext(API: .OpenGLES2))
    videoFeed.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
    videoFeed.translatesAutoresizingMaskIntoConstraints = true
    videoFeed.contentScaleFactor = 1.0
    self.view.addSubview(videoFeed)
    renderContext  = CIContext(EAGLContext: videoFeed.context)
    sessionQueue = dispatch_queue_create("dCamSession", DISPATCH_QUEUE_SERIAL)
    videoFeed.bindDrawable()
}

override public func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    startSession()
}

func createSession() -> AVCaptureSession {
    let cam = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    var input:AVCaptureInput
    do {
        input = try AVCaptureDeviceInput(device: cam)
    } catch _ as NSError {
        print("Cannot Init Cam")
        exit(EXIT_FAILURE)
    }

    //output
    let videoOut = AVCaptureVideoDataOutput()

    videoOut.videoSettings = nil
    videoOut.alwaysDiscardsLateVideoFrames = true
    videoOut.setSampleBufferDelegate(self, queue: sessionQueue)
    //connectionWithMediaType always get nil
    let connection = videoOut.connectionWithMediaType(AVMediaTypeVideo)
    if connection.supportsVideoOrientation {
        connection.videoOrientation = .Portrait
    }

    let session = AVCaptureSession()
    //make sure the stream quality good enough.
    session.sessionPreset = AVCaptureSessionPresetPhoto
    session.addInput(input)
    session.addOutput(videoOut)
    session.commitConfiguration()

    return session

}

func startSession() {
    if camSession == nil {
        camSession = createSession()
    }
    camSession.startRunning()
}

我做错什么了?

如果我删除videoOrientation比正常情况要多(但方向错误)。

没关系,您需要的只是异步调用它。

最佳答案

您的问题是您在添加videoOut作为输出之前尝试访问该连接。

这就是它异步工作的原因:在您调用connectionWithMediaType时,您的addOutput(videoOut)已经被调用。

08-19 13:08