Guardar video con AVFoundation Swift

Hola, seguí un curso de Janetworking Davidson para crear una vista de camera personalizada y save imágenes usando AVFoundation. https://www.youtube.com/watch?v=w0O3ZGUS3pk

Sin embargo, me gustaría grabar y save videos en lugar de imágenes. ¿Puede alguien ayudarme aquí? Estoy seguro de que es simple, pero la documentation de Apple está escrita en Objective-C y no puedo descifrarla.

Este es mi codigo Gracias.

import UIKit import AVFoundation class ViewController: UIViewController { var captureSession = AVCaptureSession() var sessionOutput = AVCaptureStillImageOutput() var previewLayer = AVCaptureVideoPreviewLayer() @IBOutlet var cameraView: UIView! override func viewWillAppear(animated: Bool) { let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices { if device.position == AVCaptureDevicePosition.Front{ do{ let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice) if captureSession.canAddInput(input){ captureSession.addInput(input) sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(sessionOutput){ captureSession.addOutput(sessionOutput) captureSession.startRunning() previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait cameraView.layer.addSublayer(previewLayer) previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2) previewLayer.bounds = cameraView.frame } } } catch{ print("Error") } } } } @IBAction func TakePhoto(sender: AnyObject) { if let videoConnection = sessionOutput.connectionWithMediaType(AVMediaTypeVideo){ sessionOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { buffer, error in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil) }) } } } 

Puede save grabar su video en un file creando y agregando un AVCaptureMovieFileOutput a su session de captura, y haciendo que su ViewController ajuste a AVCaptureFileOutputRecordingDelegate .

Este ejemplo registra 5 segundos de video en un file llamado "output.mov" en el directory de documentos de la aplicación.

 class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate { var captureSession = AVCaptureSession() var sessionOutput = AVCaptureStillImageOutput() var movieOutput = AVCaptureMovieFileOutput() var previewLayer = AVCaptureVideoPreviewLayer() @IBOutlet var cameraView: UIView! override func viewWillAppear(animated: Bool) { self.cameraView = self.view let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices { if device.position == AVCaptureDevicePosition.Front{ do{ let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice) if captureSession.canAddInput(input){ captureSession.addInput(input) sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(sessionOutput){ captureSession.addOutput(sessionOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait cameraView.layer.addSublayer(previewLayer) previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2) previewLayer.bounds = cameraView.frame } captureSession.addOutput(movieOutput) captureSession.startRunning() let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let fileUrl = paths[0].URLByAppendingPathComponent("output.mov") try? NSFileManager.defaultManager().removeItemAtURL(fileUrl) movieOutput.startRecordingToOutputFileURL(fileUrl, recordingDelegate: self) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { print("stopping") self.movieOutput.stopRecording() } } } catch{ print("Error") } } } } func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { print("FINISHED \(error)") // save video to camera roll if error == nil { UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path!, nil, nil, nil) } } } 

Gracias por esto. Fue muy útil para mí. Aquí hay una versión de la respuesta del Fistman rítmico portada a Swift 3 con las instrucciones de import y los methods de delegado requeridos.

 import UIKit import AVFoundation class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate { var captureSession = AVCaptureSession() var sessionOutput = AVCaptureStillImageOutput() var movieOutput = AVCaptureMovieFileOutput() var previewLayer = AVCaptureVideoPreviewLayer() @IBOutlet var cameraView: UIView! override func viewWillAppear(_ animated: Bool) { self.cameraView = self.view let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) for device in devices! { if (device as AnyObject).position == AVCaptureDevicePosition.front{ do{ let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice) if captureSession.canAddInput(input){ captureSession.addInput(input) sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(sessionOutput){ captureSession.addOutput(sessionOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait cameraView.layer.addSublayer(previewLayer) previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2) previewLayer.bounds = cameraView.frame } captureSession.addOutput(movieOutput) captureSession.startRunning() let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let fileUrl = paths[0].appendingPathComponent("output.mov") try? FileManager.default.removeItem(at: fileUrl) movieOutput.startRecording(toOutputFileURL: fileUrl, recordingDelegate: self) let delayTime = DispatchTime.now() + 5 DispatchQueue.main.asyncAfter(deadline: delayTime) { print("stopping") self.movieOutput.stopRecording() } } } catch{ print("Error") } } } } //MARK: AVCaptureFileOutputRecordingDelegate Methods func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { print("FINISHED \(error)") // save video to camera roll if error == nil { UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path, nil, nil, nil) } } 

}