【问题标题】:iOS Swift 2 Record Video AVCaptureSessioniOS Swift 2 录制视频 AVCaptureSession
【发布时间】:2023-03-05 00:08:01
【问题描述】:

我创建了一个 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
    }

【问题讨论】:

    标签: ios swift video avcapturesession


    【解决方案1】:

    您没有提及您是使用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

    【讨论】:

    • 如何捕捉刚刚录制的视频并重播?我已经放置了“视图”来显示您正在录制的内容,换句话说,“预览”了相机所看到的内容。但是我如何不将其保存在我的 photolib 中,而是捕获视频并重播呢?
    • 将视频保存在 photolib 中后,您将获得assetUrl,您可以使用它来使用 AVPlayer 或 MPMovieplayer(从 ios9 弃用)播放录制的视频
    • 是的。我注意到。如何用 AVPlayer 重写它?
    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多