Swift Merge AVasset-Videos array

后端 未结 3 1881
忘了有多久
忘了有多久 2021-02-04 20:18

I want to merge the AVAsset-arrayVideos into one single video and save it on camera roll. Raywenderlich.com has a great tutorial where two videos are merged into on

3条回答
  •  再見小時候
    2021-02-04 20:36

    You need to track the total time for all of the assets and update it for each video.

    The code in your question was rewriting the atTimeM with the current video. That's why only the first and last got included.

    It will look something like this:

    ...
    var totalTime : CMTime = CMTimeMake(0, 0)
    
    func mergeVideoArray() {
    
        let mixComposition = AVMutableComposition()
        for videoAsset in arrayVideos {
            let videoTrack = 
                mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, 
                                               preferredTrackID: Int32(kCMPersistentTrackID_Invalid))          
            do {
                if videoAsset == arrayVideos.first {
                    atTimeM = kCMTimeZero
                } else {
                    atTimeM = totalTime // <-- Use the total time for all the videos seen so far.
                }
                try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), 
                                               of: videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0], 
                                               at: atTimeM)  
                videoSize = videoTrack.naturalSize
            } catch let error as NSError {
                print("error: \(error)")
            }
            totalTime += videoAsset.duration // <-- Update the total time for all videos.
    ...
    

    You can remove the use of lastAsset.

提交回复
热议问题