2016-02-05 120 views
2

我創建了一個AVCaptureSession,並操作每個幀(變形)用戶的臉部,添加圖層等。我怎樣才能將這些幀轉換爲可以保存到相機膠捲的視頻?使用AVFoundation Swift錄製視頻

下面是如何設置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其中添加我的效果。

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

我該如何錄製視頻?

+0

我有同樣的問題嗎?你找到了解決方案嗎? – Sam

+0

什麼都沒有,讓我知道你的情況。 –

回答

2

我找到了解決問題的辦法。我也在斯威夫特工作,並有同樣的問題。我很感謝你發佈這個問題,因爲它幫助了我很多。我能夠成功處理相框,然後將它們寫入相機膠捲。我還沒有完善它,但它是可能的。

事實證明,一旦你開始搞亂AVCaptureDataOutput,你據說失去了使用AVCaptureMovieFileOutput的能力,參見討論here

您的問題的簡明解決方案可以找到here。這是我實施的版本。將sampleBuffer饋送到AVAssetWriterInput對象。

解決問題的更詳細的guide描述了需要什麼部分(即AVAssetWriter,AVAssetWriterInput和outSettings等)以及它們的樣子。

我發佈的鏈接是obj-c,但可以翻譯成swift。我希望你已經解決了你的問題。

+0

謝謝,我還沒有找到正確的方法來完成它,所以我會檢查鏈接了。如果您發現其他問題,請告訴我。 –

相關問題