如何解决如何提高 AVAssetExportSession 保存性能
我正在使用 AVAssetExportSession
保存带有一些文本/图像叠加层的视频。
它工作得很好,除了保存新视频需要很多时间,我见过其他应用程序的速度要快得多,比如快 2-4 倍。所以我想知道我做错了什么吗?
这是我的代码(为了更好地阅读错误,我删除了一些不相关的部分,如果您想看到某些功能的实现,请告诉我):
func saveVideo() {
guard let fileURL = videoMediaURL else { return }
let vidAsset = AVURLAsset(url: fileURL,options: nil)
// Create an AVMutableComposition for editing
let mutableComposition = getVideoComposition(asset: vidAsset)
let videoTrack: AVAssetTrack = mutableComposition.tracks(withMediaType: AVMediaType.video)[0]
var size = videoTrack.naturalSize
//fixing native ios rotated video
if videoTrack.preferredTransform.c == -1 {
size = CGSize(width: size.height,height: size.width)
}
let isLandscape = size.width > size.height
if videoTrack.preferredTransform.a == 1 && videoTrack.preferredTransform.d == 1 && isLandscape {
size = CGSize(width: size.height,height: size.width)
}
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(start: CMTime.zero,duration: mutableComposition.duration)
let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
var transform = videoTrack.preferredTransform
if transform.a == 1 && transform.d == 1 && isLandscape {
let diff = size.height / size.width
let scale = videoTrack.preferredTransform.xScale * diff
transform = videoTrack.preferredTransform.translatedBy(x: (-size.width * scale) / 1.65,y: videoTrack.preferredTransform.yOffset).scaledBy(x: videoTrack.preferredTransform.xScale * diff,y: videoTrack.preferredTransform.yScale * diff)
}
if transform.tx >= 3840 {
transform = videoTrack.preferredTransform.translatedBy(x: 0,y: transform.xOffset / 2)
}
layerInstruction.setTransform(transform,at: .zero)
instruction.layerInstructions = [layerInstruction]
let containerLayer = setupLayers()
let layerComposition = AVMutableVideoComposition()
layerComposition.frameDuration = CMTimeMake(value: 1,timescale: Int32(videoTrack.nominalFrameRate))
layerComposition.renderSize = size
layerComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer,in: containerLayer)
layerComposition.instructions = [instruction]
//Remove existing file
deleteFile(outputURL)
//export the video to as per your requirement conversion
if let exportSession = AVAssetExportSession(asset: mutableComposition,presetName: AVAssetExportPresetHighestQuality) {
self.exportSession = exportSession
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileType.m4v
exportSession.shouldOptimizeforNetworkUse = true
exportSession.videoComposition = layerComposition
// try to export the file and handle the status cases
exportSession.exportAsynchronously(completionHandler: {
//handle exportSession result
})
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。