我如何编辑或修剪视频开始和指向视频的特定部分

时间:2015-07-17 15:12:35

标签: swift avfoundation

如何编辑或修剪视频开始并指向视频的特定部分?

此外,我想使用滑块指出修剪开始和结束点。

1 个答案:

答案 0 :(得分:2)

func trimVideo(sourceURL: NSURL, destinationURL: NSURL, trimPoints: TrimPoints, completion: TrimCompletion?) {
    assert(sourceURL.fileURL)
    assert(destinationURL.fileURL)

    let options = [ AVURLAssetPreferPreciseDurationAndTimingKey: true ]
    let asset = AVURLAsset(URL: sourceURL, options: options)
    let preferredPreset = AVAssetExportPresetPassthrough
    if verifyPresetForAsset(preferredPreset, asset: asset) {
        let composition = AVMutableComposition()
        let videoCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
        let audioCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

        let assetVideoTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack
        let assetAudioTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first as! AVAssetTrack

        var compError: NSError?

        var accumulatedTime = kCMTimeZero
        for (startTimeForCurrentSlice, endTimeForCurrentSlice) in trimPoints {
            let durationOfCurrentSlice = CMTimeSubtract(endTimeForCurrentSlice, startTimeForCurrentSlice)
            let timeRangeForCurrentSlice = CMTimeRangeMake(startTimeForCurrentSlice, durationOfCurrentSlice)

            videoCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetVideoTrack, atTime: accumulatedTime, error: &compError)
            audioCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetAudioTrack, atTime: accumulatedTime, error: &compError)

            if compError != nil {
                NSLog("error during composition: \(compError)")
                if let completion = completion {
                    completion(compError)
                }
            }

            accumulatedTime = CMTimeAdd(accumulatedTime, durationOfCurrentSlice)
        }

        let exportSession = AVAssetExportSession(asset: composition, presetName: preferredPreset)
        exportSession.outputURL = destinationURL
        exportSession.outputFileType = AVFileTypeAppleM4V
        exportSession.shouldOptimizeForNetworkUse = true

        removeFileAtURLIfExists(destinationURL)

        exportSession.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            if let completion = completion {
                completion(exportSession.error)
            }
        })
    } else {
        NSLog("Could not find a suitable export preset for the input video")
        let error = NSError(domain: "org.linuxguy.VideoLab", code: -1, userInfo: nil)
        if let completion = completion {
            completion(error)
        }
    }
}