如何减少裁剪视频所需的时间

时间:2018-12-13 18:39:54

标签: ios swift avfoundation

我用这个问题来应用一种将视频切成正方形的方法。

在iOS中将视频裁剪为正方形[Swift 3]

代码:

func suqareCropVideo(inputURL: NSURL, completion: @escaping (_ outputURL : NSURL?) -> ())
{
    let videoAsset: AVAsset = AVAsset( url: inputURL as URL )
    let clipVideoTrack = videoAsset.tracks( withMediaType: AVMediaTypeVideo ).first! as AVAssetTrack

    let composition = AVMutableComposition()
    composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

    let videoComposition = AVMutableVideoComposition()
    videoComposition.renderSize = CGSize( width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height )
    videoComposition.frameDuration = CMTimeMake(1, 30)

    let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))


    let transform1: CGAffineTransform = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: (clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
    let transform2 = transform1.rotated(by: .pi/2)
    let finalTransform = transform2


    transformer.setTransform(finalTransform, at: kCMTimeZero)

    instruction.layerInstructions = [transformer]
    videoComposition.instructions = [instruction]

    // Export
    let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
    print ("random id = \(NSUUID().uuidString)")

    let croppedOutputFileUrl = URL( fileURLWithPath: getOutputPath( NSUUID().uuidString) ) // CREATE RANDOM FILE NAME HERE
    exportSession.outputURL = croppedOutputFileUrl
    exportSession.outputFileType = AVFileTypeQuickTimeMovie

    exportSession.exportAsynchronously() { handler -> Void in
        if exportSession.status == .completed {
            print("Export complete")
            DispatchQueue.main.async(execute: {
                completion(croppedOutputFileUrl as NSURL)
            })
            return
        } else if exportSession.status == .failed {
            print("Export failed - \(String(describing: exportSession.error))")
        }

        completion(nil)
        return
    }
}

它运作良好并显示出良好的结果,但是有一个问题。 剪切输入视频需要花费inputUrl长度的三分之一。

例如,如果inputUrl长为3分钟,则视频需要大约1分钟的剪辑时间。 如果在完全剪切之前返回主屏幕,该作业将不再运行并结束。 你能告诉我如何减少时间吗?

0 个答案:

没有答案