我想合并多个视频,我想在最终视频中保留其实际方向。这是我的代码
func mergeSelectedVideos() {
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
}
let mergedVideoURL = NSURL(fileURLWithPath: NSHomeDirectory() + "/Documents/mergedVideo.mp4")
let exporter: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!
exporter.outputFileType = AVFileTypeMPEG4
exporter.outputURL = mergedVideoURL as URL
removeFileAtURLIfExists(url: mergedVideoURL)
exporter.exportAsynchronously(completionHandler:
{
switch exporter.status
{
case AVAssetExportSessionStatus.failed:
print("failed \(String(describing: exporter.error))")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(String(describing: exporter.error))")
case AVAssetExportSessionStatus.unknown:
print("unknown\(String(describing: exporter.error))")
case AVAssetExportSessionStatus.waiting:
print("waiting\(String(describing: exporter.error))")
case AVAssetExportSessionStatus.exporting:
print("exporting\(String(describing: exporter.error))")
default:
print("-----Merged video exportation complete.\(self.mergedVideoURL)")
}
})
}
使用此代码我可以合并多个视频,但是纵向视频会在合并视频中旋转。是否有可能以某种方式合并它们,纵向视频将保持纵向,横向视频将在最终视频中保持景观?我搜索了很多,但没有找到任何。