CTR*_*x64 5 video crop ios swift
我无法裁剪视频以使其与Swift 3和iOS 10.x相适应。执行剪裁例程后,我将视频保存到我的照片库中,看起来与原始视频相同。
我使用以下帖子作为参考:使用AVFoundation裁剪AVAsset视频无法正常运行iOS 8
func suqareCropVideo(inputURL: NSURL, completion: @escaping (_ outputURL : NSURL?) -> ())
{
let videoAsset: AVAsset = AVAsset( url: inputURL as URL )
let clipVideoTrack = videoAsset.tracks( withMediaType: AVMediaTypeVideo ).first! as AVAssetTrack
let composition = AVMutableComposition()
composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = CGSize( width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height )
videoComposition.frameDuration = CMTimeMake(1, 30)
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))
let transform1: CGAffineTransform = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: (clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
let transform2 = transform1.rotated(by: .pi/2)
let finalTransform = transform2
transformer.setTransform(finalTransform, at: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
// Export
let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
print ("random id = \(NSUUID().uuidString)")
let croppedOutputFileUrl = URL( fileURLWithPath: getOutputPath( NSUUID().uuidString) ) // CREATE RANDOM FILE NAME HERE
exportSession.outputURL = croppedOutputFileUrl
exportSession.outputFileType = AVFileTypeQuickTimeMovie
exportSession.exportAsynchronously() { handler -> Void in
if exportSession.status == .completed {
print("Export complete")
DispatchQueue.main.async(execute: {
completion(croppedOutputFileUrl as NSURL)
})
return
} else if exportSession.status == .failed {
print("Export failed - \(String(describing: exportSession.error))")
}
completion(nil)
return
}
}
Run Code Online (Sandbox Code Playgroud)
用法如下所示:
if videoURL != nil {
print ("crop video")
suqareCropVideo(inputURL: self.videoURL, completion: { (outputURL) -> () in
print ("compressed url = \(String(describing: outputURL))")
// Save video to photo library
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL:outputURL! as URL)
}) { saved, error in
if saved {
print ("save successful")
}
else {
print ("save failed")
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
您实际上并未在导出器上设置视频合成
所以试试
exportSession.videoComposition = videoComposition
Run Code Online (Sandbox Code Playgroud)
在开始导出之前。
归档时间: |
|
查看次数: |
2901 次 |
最近记录: |