AVAssetWriter旋转缓冲区,用于视频方向

时间:2019-03-08 15:17:29

标签: ios swift avfoundation avassetwriter cmsamplebuffer

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

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

由于存在一些“主UI线程停止”,因此我无法根据设备方向使用avcaptureconnection.videoOrientation

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

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

1 个答案:

答案 0 :(得分:0)

由于您使用的是AVAssetWriter。试试

  private let assetWriter: AVAssetWriter
  private var adaptor: AVAssetWriterInputPixelBufferAdaptor

并像这样初始化AVAssetWriter

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

extension创建一个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])
  }