raj yadav raj yadav - 1 year ago 52
Swift Question

How I can edit or trim video start and point particular parts of video

How I can edit or trim video start and point particular parts of video?

Also I want to use slider to point out trimming start and end points.

Answer Source
func trimVideo(sourceURL: NSURL, destinationURL: NSURL, trimPoints: TrimPoints, completion: TrimCompletion?) {

    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 {

            accumulatedTime = CMTimeAdd(accumulatedTime, durationOfCurrentSlice)

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


        exportSession.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            if let completion = completion {
    } 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 {