以正确的方向合并多个视频资源 swift

Merge multiple video assets with correct orientation swift

我只是想拼接(合并)一组视频(具有正确的原始方向),而且 但是有些视频的方向不正确视频。例如,使用当前的 preferredTransform,前置视频是倒置的(即,如果您用手在左侧拍摄视频,它现在将在右侧..)而后置摄像头视频则保持原样。

我已经尝试查看很多关于此的问题,但 none 似乎解决了这个问题。我只需要视频保持原来的方向!

func merge(arrayVideos:[AVAsset], completion:@escaping (URL?, Error?) -> ()) {


          let mainComposition = AVMutableComposition()
          let compositionVideoTrack = mainComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
  compositionVideoTrack?.preferredTransform = CGAffineTransform(rotationAngle: (.pi)/2) 

          let soundtrackTrack = mainComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)

            var insertTime = CMTime.zero

          for videoAsset in arrayVideos {
            try! compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: insertTime)
            try! soundtrackTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: insertTime)

            insertTime = CMTimeAdd(insertTime, videoAsset.duration)
          }

          let outputFileURL = URL(fileURLWithPath: NSTemporaryDirectory() + "merge.mp4")

          let fileManager = FileManager()
          try? fileManager.removeItem(at: outputFileURL)

          let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)

          exporter?.outputURL = outputFileURL
          exporter?.outputFileType = AVFileType.mp4
          exporter?.shouldOptimizeForNetworkUse = true

          exporter?.exportAsynchronously {
            if let url = exporter?.outputURL{
                completion(url, nil)
            }
            if let error = exporter?.error {
                completion(nil, error)
            }
          }
        }

我解决了问题!!

参考我的回答:

How to correctly orient multiple video tracks (taken on front facing cam and back facing), before merging or during?