【发布时间】:2019-06-25 05:29:57
【问题描述】:
从图库中挑选视频后,我尝试旋转它并将其保存在图库中。当我选择一个处于横向模式的视频时,我的旋转效果很好。但是,如果我选择一个处于纵向模式的视频,并尝试以给定的角度旋转它。视频获得额外的旋转。
这是我的代码:
let currentAsset = AVAsset( url: outputFileURL)
let composition = AVMutableComposition.init()
let videoComposition = AVMutableVideoComposition()
videoComposition.frameDuration = CMTimeMake(1, 30)
videoComposition.renderScale = 1.0
let compositionCommentaryTrack: AVMutableCompositionTrack? = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)
let compositionVideoTrack: AVMutableCompositionTrack? = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
let videoDuration: CMTime = currentAsset.duration
let clipVideoTrack:AVAssetTrack = currentAsset.tracks(withMediaType: AVMediaType.video)[0]
let audioTrack: AVAssetTrack = currentAsset.tracks(withMediaType: AVMediaType.audio)[0]
try? compositionCommentaryTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, currentAsset.duration), of: audioTrack, at: kCMTimeZero)
try? compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, currentAsset.duration ), of: clipVideoTrack, at: kCMTimeZero)
var naturalSize = clipVideoTrack.naturalSize
naturalSize = CGSize.init(width: naturalSize.width, height: naturalSize.height)
videoComposition.renderSize = naturalSize
let x = naturalSize.width
let y = naturalSize.height
let scale = CGFloat(1.0)
let frontLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack!)
var rotationTransform = CGAffineTransform(translationX: x/2, y: y/2)
rotationTransform = rotationTransform.rotated(by: angle)
rotationTransform = rotationTransform.translatedBy(x: -x/2, y: -y/2)
frontLayerInstruction.setTransform(rotationTransform, at: kCMTimeZero)
// saving video in gallery
let MainInstruction = AVMutableVideoCompositionInstruction()
MainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration)
MainInstruction.layerInstructions = [frontLayerInstruction]
videoComposition.instructions = [MainInstruction]
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let videoPath = documentsPath+"/cropEditVideo.mov"
let fileManager = FileManager.default
if fileManager.fileExists(atPath: videoPath) {
try! fileManager.removeItem(atPath: videoPath)
}
var exportSession = AVAssetExportSession.init(asset: composition, presetName: AVAssetExportPresetHighestQuality)
exportSession?.outputFileType = AVFileType.mov
exportSession?.videoComposition = videoComposition
exportSession?.outputURL = URL.init(fileURLWithPath: videoPath)
.
.
.
.
我没有发布使用 AVAssetExportSession 保存视频的完整代码,因为我相信它不需要。
因此,如果我对视频应用 10 度的旋转,它会以 280 度的旋转保存。所以基本上是一个附加的,而且它只发生在肖像视频中。
任何帮助将不胜感激。
【问题讨论】:
标签: ios swift cgaffinetransform avasset avassetexportsession