Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift 2 Record Video AVCaptureSession

I created an AVCaptureSession and attached to it the front facing camera

do {
   try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
   }catch{print("err")}

Now I want to start and stop recording on touche events. How do I do this?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("touch")
        //Start Recording
    }

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("release");
        //End Recording and Save
    }
like image 986
user3916570 Avatar asked Sep 24 '15 18:09

user3916570


1 Answers

You didn't mention if you're using AVCaptureMovieFileOutput or AVCaptureVideoDataOutput as an output for your session. The former is well suited for recording a video quickly and without further coding the later is used for more advanced recording by getting chunks of CMSampleBuffer during the recording session.

For the scope of this answer I'll go with AVCaptureMovieFileOutput, here is some minimalist starting code:

import UIKit
import AVFoundation
import AssetsLibrary

class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

var captureSession = AVCaptureSession()

lazy var frontCameraDevice: AVCaptureDevice? = {
    let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]
    return devices.filter{$0.position == .Front}.first
}()

lazy var micDevice: AVCaptureDevice? = {
    return AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
}()

var movieOutput = AVCaptureMovieFileOutput()

private var tempFilePath: NSURL = {
    let tempPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("tempMovie").URLByAppendingPathExtension("mp4").absoluteString
    if NSFileManager.defaultManager().fileExistsAtPath(tempPath) {
        do {
            try NSFileManager.defaultManager().removeItemAtPath(tempPath)
        } catch { }
    }
    return NSURL(string: tempPath)!
}()

private var library = ALAssetsLibrary()


override func viewDidLoad() {
    super.viewDidLoad()
    //start session configuration
    captureSession.beginConfiguration()
    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    // add device inputs (front camera and mic)
    captureSession.addInput(deviceInputFromDevice(frontCameraDevice))
    captureSession.addInput(deviceInputFromDevice(micDevice))

    // add output movieFileOutput
    movieOutput.movieFragmentInterval = kCMTimeInvalid
    captureSession.addOutput(movieOutput)

    // start session
    captureSession.commitConfiguration()
    captureSession.startRunning()
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("touch")
    // start capture
    movieOutput.startRecordingToOutputFileURL(tempFilePath, recordingDelegate: self)

}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("release")
    //stop capture
    movieOutput.stopRecording()
}

private func deviceInputFromDevice(device: AVCaptureDevice?) -> AVCaptureDeviceInput? {
    guard let validDevice = device else { return nil }
    do {
        return try AVCaptureDeviceInput(device: validDevice)
    } catch let outError {
        print("Device setup error occured \(outError)")
        return nil
    }
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
    if (error != nil)
    {
        print("Unable to save video to the iPhone  \(error.localizedDescription)")
    }
    else
    {
        // save video to photo album
        library.writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: { (assetURL: NSURL?, error: NSError?) -> Void in
            if (error != nil) {
                print("Unable to save video to the iPhone \(error!.localizedDescription)")
            }
            })

        }
    }
}

For more informations on Camera Capture refer to WWDC 2014 - Session 508

like image 55
MAB Avatar answered Nov 08 '22 14:11

MAB