AVMutableComposition - 人像视频得到景观美化

时间:2017-03-20 09:19:39

标签: ios swift rotation avasset

我使用以下代码将多个视频合并为一个。

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)")
            }
    })
}
以上完成了这项工作。但问题是,如果我选择一个肖像视频,它会在最终导出的视频中进行美化。我需要在最终视频中保留所有视频的实际方向 我试过这些代码片段

        //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)!
        }
来自this link

。它没有用。任何帮助将不胜感激

0 个答案:

没有答案