【问题标题】:AVAssetWriter rotate buffer for video orientationAVAssetWriter 为视频方向旋转缓冲区
【发布时间】:2019-03-08 15:17:28
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: ios swift avfoundation avassetwriter cmsamplebuffer


    【解决方案1】:

    由于您使用的是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])
      }
    

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 2014-02-23
      相关资源
      最近更新 更多