我目前正在开发Swift中的一个函数,可以将视频大小调整为正方形。然而,我一直在我的函数中遇到警告,指出'tracks(withMediaType:)','naturalSize'和'duration'在iOS 16.0中被弃用。
下面是函数:
func resizeVideoToSquare(inputURL: URL, completion: @escaping (URL?) -> Void) {
let asset = AVAsset(url: inputURL)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
completion(nil)
return
}
let videoSize = videoTrack.naturalSize
let squareSize = min(videoSize.width, videoSize.height)
let outputSize = CGSize(width: squareSize, height: squareSize)
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = outputSize
videoComposition.frameDuration = CMTime(value: 1, timescale: 30)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRange(start: .zero, duration: asset.duration)
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
let translationX = (videoSize.width - squareSize) / 2
let translationY = (videoSize.height - squareSize) / 2
let translation = CGAffineTransform(translationX: -translationX, y: -translationY)
transformer.setTransform(translation, at: .zero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
let outputURL = URL.documentsDirectory.appendingPathComponent("squareVideo.mov")
if FileManager.default.fileExists(atPath: outputURL.path) {
try? FileManager.default.removeItem(at: outputURL)
}
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {
completion(nil)
return
}
exporter.outputURL = outputURL
exporter.outputFileType = .mov
exporter.videoComposition = videoComposition
exporter.exportAsynchronously {
if exporter.status == .completed {
completion(outputURL)
} else {
print("Failed to export video: \(String(describing: exporter.error))")
completion(nil)
}
}
}
1条答案
按热度按时间kg7wmglp1#
函数
tracks(withMediaType:) is deprecated.
使用代替loadTracks(withMediaType:completionHandler:)