I'm currently working on a function in Swift that resizes a video to a square. However, I've been encountering warnings in my function stating that 'tracks(withMediaType:)', 'naturalSize', and 'duration' are deprecated as of iOS 16.0.
Here is the function:
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)
}
}
}