vendredi 24 juin 2016

Recording video using AVFoundation Swift

I created a AVCaptureSession and manipulate each frame (morphing) the users face,adding layers etc. How can i turn those frames into a video that can be saved to the camera roll?

Here's how i set up 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()
}

Than i use the CMSampleBuffer to get a CIImage which i add my effects to.

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])

How can i record video doing this?

Aucun commentaire:

Enregistrer un commentaire