ios - connectionWithMediaType 返回零

标签 ios swift avcapturesession avcapture glkview

我尝试使用 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) 已经被调用。

关于ios - connectionWithMediaType 返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38341805/

相关文章:

ios - 如何确定HKQuantitySample数量类型?

ios - 使用音频单元时如何设置范围和元素

ios - Swift - 将图像添加到圆形 View

ios - 导航栏中带有大标题或搜索栏的 UIRefreshControl 的故障动画

ios - videoZoomFactor 不适用于 AVCaptureSession

iphone - 从后台返回时 AVCaptureSession 失败

ios - 如何在 Swift 中使用 libxml?

iphone - iCloud 和 GEOResourceManifestServerRemoteProxy : Lost connection to geod warning

ios - 使用 Swift 录制输出音频

ios - 将结构传递给 OCMock invokeBlockWithArgs 以获得 AVCaptureSession