如何在特定时间内快速修剪视频 [英] how to trim a video in swift for a particular time

查看:203
本文介绍了如何在特定时间内快速修剪视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a task in which I have to trim the recorded video from particular start point to particular end point as entered or selected by user. How am I supposed to do that. As I used UIVideoEditorController before but I don't want to use the default view and I want to trim the video directly.

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!)

        }
    })

我正在尝试使用此目标但未成功实现我的目标。

I am trying to achieve my goal using this but not succeeding.

错误消息:


failed可选(错误域= NSURLErrorDomain代码= -1100在此服务器上找不到
请求的URL。
UserInfo = {NSErrorFailingURLStringKey = file:/// var / mobile / Containers / Data / Application / E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4 / Do cuments / 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 Optional(Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." 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=The requested URL was not found on this server., NSUnderlyingError=0x1553c220 {Error Domain=N

错误第二次出现:


失败可选(错误域= NSURLErrorDomain代码= -3000不能
创建文件UserInfo = {NSUnderlyingError = 0x14e00000 {错误
域= NSOSStatusErrorDomain代码= -12124(null)},
NSLocalizedDescription =无法创建文件})

failed Optional(Error Domain=NSURLErrorDomain Code=-3000 "Cannot create file" UserInfo={NSUnderlyingError=0x14e00000 {Error Domain=NSOSStatusErrorDomain Code=-12124 "(null)"}, NSLocalizedDescription=Cannot create file})


推荐答案

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

I found my solution using this method and it works like a charm....

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
            }
        }
    }
}

这篇关于如何在特定时间内快速修剪视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆