如何在特定时间内快速修剪视频

Par*_*ker 10 trim ios avassetexportsession uivideoeditorcontroller swift

我正在处理一项任务,我必须将录制的视频从特定的起始点修剪为用户输入或选择的特定终点.我该怎么做呢 正如我UIVideoEditorController之前使用的,但我不想使用默认视图,我想直接修剪视频.

let FinalUrlTosave = NSURL(string: "\(newURL)")
    exportSession!.outputURL=FinalUrlTosave
    exportSession!.shouldOptimizeForNetworkUse = true
    // exportSession.outputFileType = AVFileTypeQuickTimeMovie
    exportSession!.outputFileType = AVFileTypeQuickTimeMovie;
    let start:CMTime
    let duration:CMTime
    var st = starttime.doubleValue
    var ed = endTime.doubleValue
    start = CMTimeMakeWithSeconds(st, 600)
    duration = CMTimeMakeWithSeconds(ed, 600)
    // let timeRangeForCurrentSlice = CMTimeRangeMake(start, duration)
    let range = CMTimeRangeMake(start, duration);
    exportSession!.timeRange = range

       exportSession!.exportAsynchronouslyWithCompletionHandler({
        switch exportSession!.status{
        case  AVAssetExportSessionStatus.Failed:

            print("failed \(exportSession!.error)")
        case AVAssetExportSessionStatus.Cancelled:
            print("cancelled \(exportSession!.error)")
        default:
            print("complete....complete")
            //                self.SaveVideoToPhotoLibrary(destinationURL1!)

        }
    })
Run Code Online (Sandbox Code Playgroud)

我试图用这个来实现我的目标,但没有成功.

错误信息:

failed可选(错误域= NSURLErrorDomain代码= -1100"在此服务器上找不到请求的URL."UserInfo = {NSErrorFailingURLStringKey = file:/// var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3 -C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4,NSErrorFailingURLKey = file:///var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4,NSLocalizedDescription =要求在此服务器上找不到URL.,NSUnderlyingError = 0x1553c220 {错误域= N.

第二次出错:

failed可选(错误域= NSURLErrorDomain代码= -3000"无法创建文件"UserInfo = {NSUnderlyingError = 0x14e00000 {Error Domain = NSOSStatusErrorDomain Code = -12124"(null)"},NSLocalizedDescription =无法创建文件})

Par*_*ker 21

我找到了使用这种方法的解决方案,它就像一个魅力....

func cropVideo(sourceURL1: NSURL, statTime:Float, endTime:Float)
{
    let manager = NSFileManager.defaultManager()

    guard let documentDirectory = try? manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) else {return}
    guard let mediaType = "mp4" as? String else {return}
    guard let url = sourceURL1 as? NSURL else {return}

    if mediaType == kUTTypeMovie as String || mediaType == "mp4" as String {
        let asset = AVAsset(URL: url)
        let length = Float(asset.duration.value) / Float(asset.duration.timescale)
        print("video length: \(length) seconds")

        let start = statTime
        let end = endTime

        var outputURL = documentDirectory.URLByAppendingPathComponent("output")
        do {
            try manager.createDirectoryAtURL(outputURL, withIntermediateDirectories: true, attributes: nil)
            let name = Moment.newName()
            outputURL = outputURL.URLByAppendingPathComponent("\(name).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)")
               self.saveVideoTimeline(outputURL)
            case .Failed:
                print("failed \(exportSession.error)")

            case .Cancelled:
                print("cancelled \(exportSession.error)")

            default: break
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 11

一个swift4版本.

static func cropVideo(sourceURL: URL, startTime: Double, endTime: Double, completion: ((_ outputUrl: URL) -> Void)? = nil)
{
    let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let asset = AVAsset(url: sourceURL)
    let length = Float(asset.duration.value) / Float(asset.duration.timescale)
    print("video length: \(length) seconds")

    var outputURL = documentDirectory.appendingPathComponent("output")
    do {
        try fileManager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
        outputURL = outputURL.appendingPathComponent("\(sourceURL.lastPathComponent).mp4")
    }catch let error {
        print(error)
    }

    //Remove existing file
    try? fileManager.removeItem(at: outputURL)

    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else { return }
    exportSession.outputURL = outputURL
    exportSession.outputFileType = .mp4

    let timeRange = CMTimeRange(start: CMTime(seconds: startTime, preferredTimescale: 1000),
                                end: CMTime(seconds: endTime, preferredTimescale: 1000))

    exportSession.timeRange = timeRange
    exportSession.exportAsynchronously {
        switch exportSession.status {
        case .completed:
            print("exported at \(outputURL)")
            completion?(outputURL)
        case .failed:
            print("failed \(exportSession.error.debugDescription)")
        case .cancelled:
            print("cancelled \(exportSession.error.debugDescription)")
        default: break
        }
    }
}
Run Code Online (Sandbox Code Playgroud)