ios - AVAssetWriter 为视频方向旋转缓冲区
问题描述
我正在开发一个正在使用的实时录制应用程序,Swift
但AVFoundation
我遇到了视频方向问题。我使用AVAssetWriter
而不是AVCaptureMovieFileOutput
因为我需要以方形格式记录(如果我错了,请纠正我)。
我尝试使用videoInput.transform
,但听说并非所有视频播放器都支持它。
我不能avcaptureconnection.videoOrientation
根据设备方向使用,因为有一些“主 UI 线程停止”。
我读到最好的解决方案是CMSampleBuffer
在AVCaptureVideoDataOutputSampleBufferDelegate
委托函数中旋转captureOutput(...)
。它看起来有点复杂,Apple 的文档没有多大帮助,很多帖子都在Objective-C
.
在这样做之前,我想知道是否有一些我可能会错过的解决方案。谢谢
解决方案
由于您使用的是AVAssetWriter
. 尝试,
private let assetWriter: AVAssetWriter
private var adaptor: AVAssetWriterInputPixelBufferAdaptor
AVAssetWriter
并像这样初始化,
adaptor = AVAssetWriterInputPixelBufferAdaptor(rotationAngle: AVCaptureDevice.correctOrientation)
assetWriter = AVAssetWriter(input: adaptor.assetWriterInput)
创建一个extension
for AVCaptureDevice
,相应地更改角度以进行旋转。
// 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
}
再extension
为AVAssetWriterInputPixelBufferAdaptor
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])
}
推荐阅读
- c# - c# timer 与系统时钟同步
- typescript - 如何在 VSCode 中为 typescript 类型导入配置耳语
- modelica - 如何理解Modelica模型中求解非线性方程组的失败?
- regex - 将字符串匹配为文本的正则表达式
- django - 在 Django 中定义下拉框的最简单方法是什么?
- c# - 如果这个值等于这个 json 的另一个值,则在几个 json 字段中检索一个值
- node.js - Axios GET 请求将空的 req.body 发送到服务器
- mysql - MySql 按最新日期选择用户
- c# - 如何在主视图模型和用户控制视图模型之间进行通信
- ubuntu - 转换为 PKCS12