iOS Swift 2 录制视频 AVCaptureSession

5
我创建了一个AVCaptureSession,并将前置摄像头连接到它上面。
do {
   try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
   }catch{print("err")}

现在我想在触摸事件上开始和停止录制。我该怎么做?
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
    }
1个回答

8
您没有提到您在会话中使用AVCaptureMovieFileOutput还是AVCaptureVideoDataOutput作为输出。前者非常适合快速录制视频,而无需进一步编码,后者则通过在录制会话期间获取CMSampleBuffer的块来用于更高级的录制。
对于此答案的范围,我将选择AVCaptureMovieFileOutput,这里是一些最简化的起始代码:
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)")
            }
            })

        }
    }
}

有关相机捕捉的更多信息,请参阅WWDC 2014 - Session 508


1
你如何捕捉刚刚录制的视频并重播呢? 我已经放置了一个“视图”,显示您正在录制的内容,换句话说,是相机所看到的“预览”。 但是,我该如何在不将其保存在我的照片库中的情况下捕捉视频并进行重播呢? - user4545564
在将视频保存到照片库后,您会获得assetUrl,可以使用它来使用AVPlayer或MPMovieplayer(从ios9开始已弃用)播放记录的视频。 - MAB
是的,我注意到了。我该如何使用AVPlayer重写它? - user4545564

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接