首页 > 解决方案 > AVAssetWriter 为视频方向旋转缓冲区

问题描述

我正在开发一个正在使用的实时录制应用程序,SwiftAVFoundation我遇到了视频方向问题。我使用AVAssetWriter而不是AVCaptureMovieFileOutput因为我需要以方形格式记录(如果我错了,请纠正我)。

我尝试使用videoInput.transform,但听说并非所有视频播放器都支持它。

我不能avcaptureconnection.videoOrientation根据设备方向使用,因为有一些“主 UI 线程停止”。

我读到最好的解决方案是CMSampleBufferAVCaptureVideoDataOutputSampleBufferDelegate委托函数中旋转captureOutput(...)。它看起来有点复杂,Apple 的文档没有多大帮助,很多帖子都在Objective-C.

在这样做之前,我想知道是否有一些我可能会错过的解决方案。谢谢

标签: iosswiftavfoundationavassetwritercmsamplebuffer

解决方案


由于您使用的是AVAssetWriter. 尝试,

  private let assetWriter: AVAssetWriter
  private var adaptor: AVAssetWriterInputPixelBufferAdaptor

AVAssetWriter并像这样初始化,

adaptor = AVAssetWriterInputPixelBufferAdaptor(rotationAngle: AVCaptureDevice.correctOrientation)
assetWriter = AVAssetWriter(input: adaptor.assetWriterInput)

创建一个extensionfor 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
    }

extensionAVAssetWriterInputPixelBufferAdaptor

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])
  }

推荐阅读