[英]iOS how to correctly handle orientation when capturing video using AVAssetWriter
[英]AVAssetWriter rotate buffer for video orientation
我正在使用AVFoundation
在Swift
进行实时录制应用程序,但视频方向出现问题。 我使用AVAssetWriter
而不是AVCaptureMovieFileOutput
因为我需要以正方形格式记录(如果我记错了,请更正)。
我尝试使用videoInput.transform
但听说并非所有视频播放器都支持它。
我无法基于设备方向使用avcaptureconnection.videoOrientation
,因为有一些“主UI线程停止”。
我读到最好的解决方案是旋转AVCaptureVideoDataOutputSampleBufferDelegate
委托函数captureOutput(...)
的CMSampleBuffer
。 看起来有点复杂,Apple的文档没有太大帮助,许多帖子都在Objective-C
。
在采取这种方式之前,我想知道是否有一些我可能会错过的解决方案。 谢谢
由于您正在使用AVAssetWriter
。 尝试,
private let assetWriter: AVAssetWriter
private var adaptor: AVAssetWriterInputPixelBufferAdaptor
然后像这样初始化AVAssetWriter
,
adaptor = AVAssetWriterInputPixelBufferAdaptor(rotationAngle: AVCaptureDevice.correctOrientation)
assetWriter = AVAssetWriter(input: adaptor.assetWriterInput)
为AVCaptureDevice
创建extension
,相应地更改角度以旋转。
// The angle by which to rotate captured media, based on the current orientation, so that it looks correctly oriented to the user.
var correctOrientation: CGFloat {
let angle: CGFloat
switch(UIDevice.current.orientation) {
case .portraitUpsideDown: angle = -CGFloat.pi / 2 // Play around with these values
case .landscapeLeft: angle = -CGFloat.pi
case .landscapeRight: angle = 0
case .portrait: angle = CGFloat.pi / 2
default: angle = CGFloat.pi / 2
}
return angle
}
为AVAssetWriterInputPixelBufferAdaptor
创建另一个extension
extension AVAssetWriterInputPixelBufferAdaptor {
convenience init(rotationAngle: CGFloat) {
let input = AVAssetWriterInput(width: UIDevice.activeFormat.width, height: UIDevice.activeFormat.height)
input.transform = CGAffineTransform(rotationAngle: rotationAngle)
self.init(
assetWriterInput: input,
sourcePixelBufferAttributes: [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, // use whatever format you used
kCVPixelBufferWidthKey as String: UIDevice.activeFormat.width,
kCVPixelBufferHeightKey as String: UIDevice.activeFormat.height])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.