我只是想在捕获视频后将其旋转 90 度。我遵循了这个线程中的答案:iOS 如何在使用 AVAssetWriter 捕获视频时正确处理方向
当我的资产完成写入后,我调用该方法来设置视频的属性,然后将其导出。
assetWriter?.finishWriting(completionHandler: {[unowned self] () -> Void in
let firstAsset = AVURLAsset(url: self.movieURL() as URL)
guard let exporter = AVAssetExportSession(asset: firstAsset, presetName: AVAssetExportPresetHighestQuality) else { return }
guard let vidComp = self.getVideoComposition(asset: firstAsset,
videoSize: CGSize(width:1280,
height:720)) else {
print("Unable to create video composition")
return
}
print(vidComp.instructions)
exporter.videoComposition = vidComp
exporter.outputURL = self.movieURL() as URL
exporter.outputFileType = AVFileType.mov
exporter.exportAsynchronously() {
DispatchQueue.main.async(){
self.activityTextStatus.text = ""
fileURLSenderVal = self.movieURL() as URL
let manageCaptureVC = self.storyboard?.instantiateViewController(withIdentifier: "ManageCaptureVC") as! ManageCaptureVC
manageCaptureVC.fileURL = fileURLSenderVal
manageCaptureVC.takePhotoSelected = self.takePhotoSelected
manageCaptureVC.delegate = self
self.present(manageCaptureVC, animated: true, completion: nil)
}
}
这是 getVideoComposition 函数。请注意,我通过删除任何会检查方向或尺寸的逻辑来强制旋转,否则会这样做。它应该始终应用旋转:
private func getVideoComposition(asset: AVAsset, videoSize: CGSize) -> AVMutableVideoComposition? {
guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first else {
print("Unable to get video tracks")
return nil
}
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = videoSize
let seconds: Float64 = Float64(1.0 / videoTrack.nominalFrameRate)
videoComposition.frameDuration = CMTimeMakeWithSeconds(seconds, 600);
let layerInst = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
var transforms = asset.preferredTransform
transforms = transforms.concatenating(CGAffineTransform(rotationAngle: CGFloat(90.0 * .pi / 180)))
transforms = transforms.concatenating(CGAffineTransform(translationX: videoSize.width, y: 0))
layerInst.setTransform(transforms, at: kCMTimeZero)
let inst = AVMutableVideoCompositionInstruction()
inst.backgroundColor = UIColor.black.cgColor
inst.layerInstructions = [layerInst]
inst.timeRange = CMTimeRange(start: kCMTimeZero, duration: asset.duration)
videoComposition.instructions = [inst]
return videoComposition
}
但是没有应用旋转。
我不知道这是否有帮助,但我打印了 vidComp 的说明:
[AVVideoCompositionInstruction {
EndTime = {
epoch = 0;
flags = 1;
timescale = 600;
value = 1301;
};
LayerStack = (
{
ConstantAffineMatrix = (
"6.123233995736766e-17",
1,
"-1",
"6.123233995736766e-17",
1280,
0
);
ConstantCropRectangle = {
Height = "1.797693134862316e+308";
Width = "1.797693134862316e+308";
X = "-8.988465674311579e+307";
Y = "-8.988465674311579e+307";
};
ConstantOpacity = 1;
SourceVideoTrackID = 1;
}
);
StartTime = {
epoch = 0;
flags = 1;
timescale = 1;
value = 0;
};
}]