how to trim a video in swift for a particular time

Parv Bhasker

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.

Error message:

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

Error occured second time:

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

Parv Bhasker

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

Swift 5

    func cropVideo(sourceURL1: URL, statTime:Float, endTime:Float)
{
    let manager = FileManager.default

    guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return}
    let mediaType = "mp4"
    if mediaType == kUTTypeMovie as String || mediaType == "mp4" as String {
        let asset = AVAsset(url: sourceURL1 as 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.appendingPathComponent("output")
        do {
            try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
            outputURL = outputURL.appendingPathComponent("\(UUID().uuidString).\(mediaType)")
        }catch let error {
            print(error)
        }

        //Remove existing file
        _ = try? manager.removeItem(at: outputURL)


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

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

        exportSession.timeRange = timeRange
        exportSession.exportAsynchronously{
            switch exportSession.status {
            case .completed:
                print("exported at \(outputURL)")
            case .failed:
                print("failed \(exportSession.error)")

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

            default: break
            }
        }
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to trim the video file and convert to 20 seconds video with Swift?

From Dev

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

From Dev

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

From Dev

Windows Media Player: How to start playing a video at a particular time offset?

From Dev

How to trim a large video with ffmpeg?

From Dev

How to trim a large video with ffmpeg?

From Dev

How to crop video to a particular size?

From Dev

How to trim Array items in swift?

From Dev

C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

From Dev

C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

From Dev

How can I extract an image from a particular time of a video in Xubuntu 16.04?

From Dev

How to trim a video in android using UI?

From Dev

How to trim video in android (without ffmpeg)?

From Dev

Python video editing -- How to trim videos

From Dev

How do I trim a video using Handbrake?

From Dev

How to compress output video with trim using FFMPEG

From Dev

How to apply filter to Video real-time using Swift

From Dev

How to record video and play audio at the same time (swift tutorial)

From Dev

How to trim the video file and convert to 15 seconds video with iOS SDK?

From Dev

Trim Particular String

From Dev

How to schedule a request at a particular time?

From Dev

How to display notification at a particular time

From Dev

How to Trim a String in Swift based on a character

From Dev

Setting particular Interval of time for DatePicker (Minimum and Maximum Time) Swift 3

From Dev

Trim Audio to Video Length

From Dev

Getting Current Time of a Video (Player - Swift)

From Dev

How to check whether a time is between particular range?

From Dev

How to decrease running time of this particular solution?

From Dev

How to make a function run for a particular time period?

Related Related

  1. 1

    How to trim the video file and convert to 20 seconds video with Swift?

  2. 2

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

  3. 3

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

  4. 4

    Windows Media Player: How to start playing a video at a particular time offset?

  5. 5

    How to trim a large video with ffmpeg?

  6. 6

    How to trim a large video with ffmpeg?

  7. 7

    How to crop video to a particular size?

  8. 8

    How to trim Array items in swift?

  9. 9

    C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

  10. 10

    C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

  11. 11

    How can I extract an image from a particular time of a video in Xubuntu 16.04?

  12. 12

    How to trim a video in android using UI?

  13. 13

    How to trim video in android (without ffmpeg)?

  14. 14

    Python video editing -- How to trim videos

  15. 15

    How do I trim a video using Handbrake?

  16. 16

    How to compress output video with trim using FFMPEG

  17. 17

    How to apply filter to Video real-time using Swift

  18. 18

    How to record video and play audio at the same time (swift tutorial)

  19. 19

    How to trim the video file and convert to 15 seconds video with iOS SDK?

  20. 20

    Trim Particular String

  21. 21

    How to schedule a request at a particular time?

  22. 22

    How to display notification at a particular time

  23. 23

    How to Trim a String in Swift based on a character

  24. 24

    Setting particular Interval of time for DatePicker (Minimum and Maximum Time) Swift 3

  25. 25

    Trim Audio to Video Length

  26. 26

    Getting Current Time of a Video (Player - Swift)

  27. 27

    How to check whether a time is between particular range?

  28. 28

    How to decrease running time of this particular solution?

  29. 29

    How to make a function run for a particular time period?

HotTag

Archive