Я разрабатываю приложение с настраиваемым видеомагнитофоном, и я должен поставить над ним водяной знак.С записью все идет хорошо, но когда я пытаюсь поставить водяной знак, видео экспортируется с другой ориентацией, иногда оно плохо обрезается.Результат корректен только для устройства в горизонтальной ориентации справа.
Вот код функции, которую я использую для наложения водяного знака на видео:
func addWatermarkToVideo(_ videoURL: URL, completion:@escaping (URL) -> Void) {
let videoAsset = AVURLAsset.init(url: videoURL)
let mixComposition = AVMutableComposition.init()
let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
do {
let clipVideoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first
try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: clipVideoTrack!, at: kCMTimeZero)
compositionVideoTrack.preferredTransform = (videoAsset.tracks(withMediaType: AVMediaTypeVideo).first?.preferredTransform)!
let layer = CALayer.init()
layer.contents = UIImage.init(named: "VideoWatermark")?.cgImage
layer.frame = CGRect.init(x: 10, y: 10, width: 300, height: 100)
let videoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first
let videoSize = videoTrack!.naturalSize
let parentLayer = CALayer.init()
let videoLayer = CALayer.init()
parentLayer.frame = CGRect.init(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
videoLayer.frame = CGRect.init(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(layer)
let videoComp = AVMutableVideoComposition.init()
videoComp.renderSize = videoSize
videoComp.frameDuration = CMTimeMake(1, 30)
videoComp.animationTool = AVVideoCompositionCoreAnimationTool.init(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
let instruction = AVMutableVideoCompositionInstruction.init()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)
let mixVideoTrack = mixComposition.tracks(withMediaType: AVMediaTypeVideo).first
let layerInstruction = AVMutableVideoCompositionLayerInstruction.init(assetTrack: mixVideoTrack!)
layerInstruction.setTransform((clipVideoTrack?.preferredTransform)!, at: kCMTimeZero)
instruction.layerInstructions = [layerInstruction]
videoComp.instructions = [instruction]
let assetExport = AVAssetExportSession.init(asset: mixComposition, presetName: AVAssetExportPreset1280x720)
assetExport?.videoComposition = videoComp
let videoName = "\(Date.init().timeIntervalSince1970).mp4"
let exportURL = URL.init(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(videoName)
assetExport?.outputFileType = AVFileTypeMPEG4
assetExport?.outputURL = exportURL
assetExport?.shouldOptimizeForNetworkUse = true
assetExport?.exportAsynchronously(completionHandler: {
NSLog("Export status: \(String(describing: assetExport?.status.rawValue))")
completion(exportURL)
})
} catch let error as NSError {
print("\(error), \(error.localizedDescription)")
}
}
Я попытался найти свою проблему, но нетрезультат был, наконец, полезным для меня, я понятия не имею, что я делаю здесь неправильно.
Любая помощь будет высоко оценена, заранее спасибо всем, кто мне поможет.