1

How to combine video clips with different orientation using AVFoundation

I have gone with the above answer and is going good. But i am facing a problem that audio of the video is being removed. Even all of my videos have voice. But after merging the exported video is mute. Can anyone help. Thanks in Advance.

Community
  • 1
  • 1
Mayank Barnwal
  • 123
  • 1
  • 12

1 Answers1

0

I was also facing the same problem, but i got the solution. Swift 4.2 version.

 // Merge All videos.
    func mergeAllVideos(completionHandler: @escaping(Bool)->Void){
        mixComposition = AVMutableComposition.init()

        // To capture video.
        let compositionVideoTrack = mixComposition?.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)

        // To capture audio.
        let compositionAudioTrack = mixComposition?.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
        var nextCliptStartTime: CMTime = CMTime.zero

        // Iterate video array.
        for file_url in Constants.videoFileNameArr{
            // Do Merging here.
            let videoAsset = AVURLAsset.init(url: file_url)
            let timeRangeInAsset = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration);
            do{
                // Merge video.
                try compositionVideoTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: nextCliptStartTime)

                // Merge Audio
                try compositionAudioTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: nextCliptStartTime)
            }catch{
                print(error)
            }

            // Increment the time to which next clip add.
            nextCliptStartTime = CMTimeAdd(nextCliptStartTime, timeRangeInAsset.duration)
        }

        // Add rotation to make it portrait.
        let rotationTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
        compositionVideoTrack!.preferredTransform = rotationTransform

        // Save final file.
        self.saveFinalFile(mixComposition!){
            isDone in
            completionHandler(true)
        }
    }
Ravi Sharma
  • 975
  • 11
  • 29