1
我下面下面的代碼爲正方形視頻組合夫特:方形視頻組合
func completeWithVideoAtURL(input: NSURL) {
let asset = AVAsset(url: input as URL)
let output = NSURL(fileURLWithPath: NSHomeDirectory() + "/Documents/Video.mp4")
let session = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
session.videoComposition = self.squareVideoCompositionForAsset(asset: asset)
session.outputURL = output as URL
session.outputFileType = AVFileTypeMPEG4
session.shouldOptimizeForNetworkUse = true
session.exportAsynchronously(completionHandler: {() -> Void in
DispatchQueue.main.async(execute: {() -> Void in
// do something with the output
print("\(output)")
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: output as URL)
}) { saved, error in
if saved {
print("saved to gallery")
}
}
})
})
}
func squareVideoCompositionForAsset(asset: AVAsset) -> AVVideoComposition {
let track = asset.tracks(withMediaType: AVMediaTypeVideo)[0]
let length = max(track.naturalSize.width, track.naturalSize.height)
var transform = track.preferredTransform
let size = track.naturalSize
let scale: CGFloat = (transform.a == -1 && transform.b == 0 && transform.c == 0 && transform.d == -1) ? -1 : 1 // check for inversion
transform = transform.translatedBy(x: scale * -(size.width - length)/2, y: scale * -(size.height - length)/2)
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
transformer.setTransform(transform, at: kCMTimeZero)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: kCMTimePositiveInfinity)
instruction.layerInstructions = [transformer]
let composition = AVMutableVideoComposition()
composition.frameDuration = CMTime(value: 1, timescale: 30)
composition.renderSize = CGSize(width: length, height: length)
composition.instructions = [instruction]
return composition
}
從squareVideoCompositionForAsset()函數I採取最大值長度 track.naturalSize之間。寬度 & track.naturalSize.height因爲我不想裁剪視頻的任何部分部分。如果我取最小值,對於縱向視頻,它會剪切視頻的較低部分,對於橫向視頻,它會剪切一些左邊的&視頻的右側部分。
- 對於景觀的視頻,輸出是正常
- 但對於人像視頻輸出就像下面的圖片
韋迪o得到左側。視頻是否可以居中?任何援助將是偉大的,並遺憾長時間的解釋。
感謝分享! – scaryguy