我正在尝试将视频剪辑为正方形,但是遇到了麻烦。 我想我可以裁剪为正方形,但是显示黑屏。 但是我不知道如何解决。
guard let originUrl = URL(string: origin) else { return }
let videoAsset = AVAsset(url: originUrl)
guard let videoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first else { return }
let videoComposition = AVMutableVideoComposition()
videoComposition.frameDuration = CMTimeMake(1, 30)
videoComposition.renderSize = CGSize(width: videoTrack.naturalSize.height, height: videoTrack.naturalSize.height)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
let transformer = AVMutableVideoCompositionLayerInstruction.init(assetTrack: videoTrack)
let t1 = CGAffineTransform(translationX: videoTrack.naturalSize.height, y: 0)
let t2 = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
t1.concatenating(t2)
transformer.setTransform(t1, at: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
let exportPath = documentPath + "/" + defineFileName() // THIS IS JUST DEFINE RANDOM NAME
let exportUrl = URL(fileURLWithPath: exportPath)
let exporter = AVAssetExportSession.init(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)
exporter?.videoComposition = videoComposition
exporter?.outputURL = exportUrl
exporter?.outputFileType = AVFileTypeQuickTimeMovie
exporter?.exportAsynchronously(completionHandler: { () -> Void in
let library = ALAssetsLibrary()
if library.videoAtPathIs(compatibleWithSavedPhotosAlbum: exportUrl) {
library.writeVideoAtPath(toSavedPhotosAlbum: exportUrl, completionBlock: nil)
}
})