我正在通过使用 AVFoundation 和 AVMutableComposition 缩放单个视频来创建视频组合。当我应用 1 以外的任何缩放比例(更大或更小)时,最终结果会出现颜色偏移。 无论将视频用作源还是将预设/格式用作目标(MOV/MP4、ProRes/H24...),我都会遇到此问题。
这是相关代码,灵感来自另一个 StackOverflow 问题 (Swift Video Resizer AVAsset)
func resizer(inputURL: URL , completion: @escaping (URL?) -> Void ){
let videoAsset = AVAsset(url: inputURL) as AVAsset
let clipVideoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first! as AVAssetTrack
let composition = AVMutableComposition()
composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = clipVideoTrack.naturalSize
videoComposition.frameDuration = CMTimeMake(1, 30)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: clipVideoTrack.asset!.duration)
let transformer : AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
// If anything that 1 on both, colors are shifted!
let transform = CGAffineTransform(scaleX: 1.001, y: 1.001)
transformer.setTransform(transform, at: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
// Export part, left for facility
let exporter = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
exporter.videoComposition = videoComposition
let outputURL = URL(fileURLWithPath: "/path/to/destination/video.mov")
exporter.outputURL = outputURL
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.exportAsynchronously(completionHandler: { () -> Void in
completion(outputURL)
})
}
最佳答案
一个解决方案是在视频结束时重置转换:
// Add this line to fix the issue:
transformer.setTransform(CGAffineTransform.identity, at: kCMTimeZero + clipVideoTrack.asset!.duration)
// Before this lines:
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
不知道为什么,但如果您有多个轨道用于合成,也可以工作。
关于swift - AVFoundation:缩放视频改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888394/