I have used the following code to merge multiple videos to one.
func mergeMultipleVideos() {
let composition = AVMutableComposition()
let videoTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
let audioTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
var time: Double = 0.0
for video in self.arrayOfSelectedVideoURL {
let sourceAsset = AVAsset(url: video as URL)
let videoAssetTrack = sourceAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
let audioAssetTrack = sourceAsset.tracks(withMediaType: AVMediaTypeAudio)[0]
let atTime = CMTime(seconds: time, preferredTimescale:1)
do{
try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, sourceAsset.duration) , of: videoAssetTrack, at: atTime)
try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, sourceAsset.duration) , of: audioAssetTrack, at: atTime)
}catch{
print("-----Something wrong.")
}
time += sourceAsset.duration.seconds
}
mergeVideoURL = NSURL(fileURLWithPath: NSHomeDirectory() + "/Documents/mergeVideo.mp4")
let exporter: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!
exporter.outputFileType = AVFileTypeMPEG4
exporter.outputURL = mergeVideoURL as URL
exporter.exportAsynchronously(completionHandler:
{
switch exporter.status
{
case AVAssetExportSessionStatus.failed:
print("failed \(exporter.error)")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(exporter.error)")
case AVAssetExportSessionStatus.unknown:
print("unknown\(exporter.error)")
case AVAssetExportSessionStatus.waiting:
print("waiting\(exporter.error)")
case AVAssetExportSessionStatus.exporting:
print("exporting\(exporter.error)")
default:
print("-----Merge video exportation complete.\(self.mergeVideoURL)")
}
})
}
the above done the job. But the problem is, if I select a portrait video, it gets landscaped in the final exported video. I need to keep the actual orientation all videos in my final video.
I have tried with these code snippets
//video orientation let assetVideoTrack = (sourceAsset.tracks(withMediaType: AVMediaTypeVideo)).last let compositionVideoTrack = (composition.tracks(withMediaType: AVMediaTypeVideo)).last if ((assetVideoTrack?.isPlayable)! && (compositionVideoTrack?.isPlayable)!) { compositionVideoTrack?.preferredTransform = (assetVideoTrack?.preferredTransform)! }
from this link . It didn't work. Any help would be appreciated