xcode Swift将录制的视频保存为mov或mp4

时间:2016-01-20 05:33:05

标签: xcode swift video save avcapturesession

我一直很难找到使用AVCaptureSession保存录制视频的方法

这是我的代码:

    @IBOutlet weak var tv: UIView!
    var session:AVCaptureSession?
    var output: AVCaptureVideoDataOutput?
    var previewLayer: AVCaptureVideoPreviewLayer?
    var out:AVCaptureMovieFileOutput!
    var outPath:NSURL?

...在视图didload函数

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let filemgr = NSFileManager.defaultManager()
        let documentsURL = filemgr.URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask)[0]
        outPath = documentsURL.URLByAppendingPathComponent("temp")

        session = AVCaptureSession()
        session!.sessionPreset = AVCaptureSessionPresetLow

        let camera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        var deviceInput:AVCaptureDeviceInput?

        do{
            try deviceInput = AVCaptureDeviceInput(device: camera)
        }catch{
        }
        session?.addInput(deviceInput)
        previewLayer = AVCaptureVideoPreviewLayer(session: session)
        let frame = CGRect(x: 0, y: 0, width: self.tv.frame.width, height: self.tv.frame.height)
        tv.layer.addSublayer(previewLayer!)
        previewLayer?.frame = frame
        session?.startRunning()

记录按钮操作

        let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self
        out = AVCaptureMovieFileOutput()
        session?.addOutput(out)
        out.startRecordingToOutputFileURL(outPath, recordingDelegate: recordingDelegate)

...停止按钮操作

        out.stopRecording()

..和委托函数

    func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outPath: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!){
        print("record fin")
        return
    }
    func captureOutput(captureOutPut: AVCaptureFileOutput!, didStartRecordingTOOutputFileAtURL outPath: NSURL!, fromConnections connections: [AnyObject]!){
        print("record start")
        return
    }

感谢您的帮助:)

修改 以下是一些其他细节

  

代码中没有错误或警告,应用程序运行正常   相机预览显示但问题是保存录制的视频,当调用out.startRecordingToOutputFileURL(outPath,recordingDelegate:recordingDelegate)时,它不保存任何文件

1 个答案:

答案 0 :(得分:1)

如果有人碰巧遇到与我相同的问题,这就是解决方案

在委托函数didfinishrecording

中添加此代码
    let library = PHPhotoLibrary.sharedPhotoLibrary()
    library.performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(outPath)!
        }, completionHandler: {success, error in
            NSLog("Finished saving asset. %@", (success ? "Success." : error!))
    })

问候

相关问题