使用AVFoundation Swift录制视频

时间:2016-02-05 15:57:59

标签: ios swift avfoundation

我创建了一个AVCaptureSession并操纵用户面对的每一帧(变形),添加图层等。如何将这些帧转换为可以保存到相机胶卷的视频?

以下是我设置AVCaptureSession

的方法
func setupCapture() {

    let session : AVCaptureSession = AVCaptureSession()
    session.sessionPreset = AVCaptureSessionPreset640x480


    let device : AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    let deviceInput : AVCaptureDeviceInput = try! AVCaptureDeviceInput(device: device)


    if session.canAddInput(deviceInput) {
        session.addInput(deviceInput)
    }

    stillImageOutput = AVCaptureStillImageOutput()


    videoDataOutput = AVCaptureVideoDataOutput()

    let rgbOutputSettings = [kCVPixelBufferPixelFormatTypeKey as String: NSNumber(unsignedInt: kCMPixelFormat_32BGRA)]

    videoDataOutput.videoSettings = rgbOutputSettings
    videoDataOutput.alwaysDiscardsLateVideoFrames = true

    videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL)
    videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue)

    if session.canAddOutput(videoDataOutput) {
        session.addOutput(videoDataOutput)
    }
    videoDataOutput.connectionWithMediaType(AVMediaTypeVideo).enabled = false

    effectiveScale = 1.0

    previewLayer = AVCaptureVideoPreviewLayer(session: session)
    previewLayer.backgroundColor = UIColor.blackColor().CGColor
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspect
    let rootLayer : CALayer = previewView.layer
    rootLayer.masksToBounds = true
    previewLayer.frame = rootLayer.bounds
    rootLayer.addSublayer(previewLayer)
    session.startRunning()
}

我使用CMSampleBuffer来获得CIImage我将效果添加到。{/ p>

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

    let pixelBuffer : CVPixelBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)!
    let attachments : CFDictionaryRef = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, pixelBuffer, CMAttachmentMode( kCMAttachmentMode_ShouldPropagate))!

    let ciImage : CIImage = CIImage(CVPixelBuffer: pixelBuffer, options: attachments as? [String : AnyObject])

我如何录制视频呢?

1 个答案:

答案 0 :(得分:2)

我找到了解决问题的方法。我也在Swift工作,并有同样的问题。我很感谢你发布这个问题,因为它给了我很多帮助。我能够成功处理帧然后将它们写入相机胶卷。我没有完善它,但它是可能的。

事实证明,一旦你开始搞乱AVCaptureDataOutput,你就会失去使用AVCaptureMovieFileOutput的能力,请参阅讨论here

可以找到问题的简明解决方案here。这是我实施的版本。将sampleBuffer提供给AVAssetWriterInput对象。

解决问题的更详细guide描述了需要哪些部分(即AVAssetWriter,AVAssetWriterInput和outSettings等)以及它们的外观。

我发布的链接是obj-c,但可以翻译成swift。我希望你已经解决了你的问题。