gpt4 book ai didi

ios - 记录裁剪视频方形长宽比 AVCaptureSession

转载 作者:行者123 更新时间:2023-11-29 05:52:03 25 4
gpt4 key购买 nike

如何使用 AVCaptureSession 录制方形视频?如果在录制时不可能,那么我如何在 didFinishRecordingTo 委托(delegate)方法中裁剪它?

提前致谢!

最佳答案

您可以使用此演示代码录制方形视频:https://github.com/DarshanRlogical/DKCustomCamera

您可以使用以下方法裁剪视频:

func manageCroppingToSquare(filePath: URL , completion: @escaping (_ outputURL : URL?) -> ()) {

// output file
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let outputPath = documentsURL?.appendingPathComponent("squareVideo.mov")
if FileManager.default.fileExists(atPath: (outputPath?.path)!) {
do {
try FileManager.default.removeItem(atPath: (outputPath?.path)!)
}
catch {
print ("Error deleting file")
}
}

//input file
let asset = AVAsset.init(url: filePath)
print (asset)
let composition = AVMutableComposition.init()
composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

//input clip
let clipVideoTrack = asset.tracks(withMediaType: AVMediaTypeVideo)[0]

//make it square
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = CGSize(width: CGFloat(clipVideoTrack.naturalSize.height), height: CGFloat(clipVideoTrack.naturalSize.height))
videoComposition.frameDuration = CMTimeMake(1, 30)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))

//rotate to potrait
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
let t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
let t2: CGAffineTransform = t1.rotated(by: .pi/2)
let finalTransform: CGAffineTransform = t2
transformer.setTransform(finalTransform, at: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]

//exporter
let exporter = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetMediumQuality)
exporter?.outputFileType = AVFileTypeQuickTimeMovie
exporter?.outputURL = outputPath
exporter?.videoComposition = videoComposition

exporter?.exportAsynchronously() { handler -> Void in
if exporter?.status == .completed {
print("Export complete")
DispatchQueue.main.async(execute: {
completion(outputPath)
})
return
} else if exporter?.status == .failed {
print("Export failed - \(String(describing: exporter?.error))")
}
completion(nil)
return
}
}

我希望这段代码对您有用。

关于ios - 记录裁剪视频方形长宽比 AVCaptureSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55572455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com