从Swift中的AVCaptureSession获取输出以发送到服务器

iam*_*esy 16 video stream ios avcapturesession swift

我设法写了一些打开相机并预览视频的代码.我现在想要从输出捕获帧以发送到理想编码为H.264的服务器

这是我得到的:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var previewLayer : AVCaptureVideoPreviewLayer?

    // If we find a device we'll store it here for later use
    var captureDevice : AVCaptureDevice?

    override func viewDidLoad() {
        super.viewDidLoad()            
        // Do any additional setup after loading the view, typically from a nib.

        captureSession.sessionPreset = AVCaptureSessionPresetHigh

        let devices = AVCaptureDevice.devices()

        // Loop through all the capture devices on this phone
        for device in devices {
            // Make sure this particular device supports video
            if (device.hasMediaType(AVMediaTypeVideo)) {
                // Finally check the position and confirm we've got the back camera
                if(device.position == AVCaptureDevicePosition.Back) {
                    captureDevice = device as? AVCaptureDevice
                    if captureDevice != nil {
                        println("Capture device found")
                        beginSession()
                    }
                }
            }
        }

    }

    func beginSession() {

        var err : NSError? = nil
        captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))

        if err != nil {
            println("error: \(err?.localizedDescription)")
        }

        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.view.layer.addSublayer(previewLayer)
        previewLayer?.frame = self.view.layer.frame

        captureSession.startRunning()

    }

}
Run Code Online (Sandbox Code Playgroud)

这会成功打开相机,我可以预览素材.

我发现这个Objective C代码看起来像输出但我不知道如何将它转换为swift.它使用AVCaptureVideoDataOutput,AVAssetWriter,AVAssetWriterInput和AVAssetWriterInputPixelBufferAdaptor将帧写入H.264编码的电影文件.

可以同时使用AVCaptureVideoDataOutput和AVCaptureMovieFileOutput吗?

有人可以帮助转换它或给我指示如何从我当前的代码中获取帧?

pte*_*fil 3

Apple 在 ObjectiveC 中有一个示例项目 AVCam 可以处理这些事情。

这是关于在 Swift 中使用 AVCamera 的另一个问题。

我个人用过这个https://github.com/alex-chan/AVCamSwift,效果很好。我只需在 Xcode 中将其转换为最新的 Swift 语法即可,效果很好。

另一个建议是使用您找到的 ObjectiveC 代码,并通过桥接标头将其导入到 Swift 代码中。