How to trim the video using AVFoundation

后端 未结 4 1662
醉话见心
醉话见心 2020-12-02 17:51

Iam able to record the video by using AVFoundation or UIImagePickerController. But i am unable to trim the video from one particular second to another particular duration/ti

4条回答
  •  攒了一身酷
    2020-12-02 18:20

    Swift version of above

    import UIKit
    import AVFoundation
    import MobileCoreServices
    
    func pickVideo(){
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            let videoRecorder = UIImagePickerController()
            videoRecorder.sourceType = .Camera
            videoRecorder.mediaTypes = [kUTTypeMovie as String]
            videoRecorder.allowsEditing = true
            videoRecorder.delegate = self
    
            presentViewController(videoRecorder, animated: true, completion: nil)
        }
    }
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        let manager = NSFileManager.defaultManager()
    
        guard let documentDirectory = try? manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) else {return}
        guard let mediaType = info[UIImagePickerControllerMediaType] as? String else {return}
        guard let url = info[UIImagePickerControllerMediaURL] as? NSURL else {return}
    
        if mediaType == kUTTypeMovie as String || mediaType == kUTTypeVideo as String {
            let asset = AVAsset(URL: url)
            let length = Float(asset.duration.value) / Float(asset.duration.timescale)
            print("video length: \(length) seconds")
    
            let start = info["_UIImagePickerControllerVideoEditingStart"] as? Float
            let end = info["_UIImagePickerControllerVideoEditingEnd"] as? Float
    
    
            var outputURL = documentDirectory.URLByAppendingPathComponent("output")
    
    
            do {
                try manager.createDirectoryAtURL(outputURL, withIntermediateDirectories: true, attributes: nil)
                outputURL = outputURL.URLByAppendingPathComponent("output.mp4")
            }catch let error {
                print(error)
            }
    
            //Remove existing file
             _ = try? manager.removeItemAtURL(outputURL)
    
    
            guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {return}
            exportSession.outputURL = outputURL
            exportSession.outputFileType = AVFileTypeMPEG4
    
            let startTime = CMTime(seconds: Double(start ?? 0), preferredTimescale: 1000)
            let endTime = CMTime(seconds: Double(end ?? length), preferredTimescale: 1000)
            let timeRange = CMTimeRange(start: startTime, end: endTime)
    
            exportSession.timeRange = timeRange
            exportSession.exportAsynchronouslyWithCompletionHandler{
                switch exportSession.status {
                case .Completed:
                    print("exported at \(outputURL)")
    
                case .Failed:
                    print("failed \(exportSession.error)")
    
                case .Cancelled:
                    print("cancelled \(exportSession.error)")
    
                default: break
                }
            }
        }
    }
    

提交回复
热议问题