Ios 用于视频定向的AVAssetWriter旋转缓冲区

Ios 用于视频定向的AVAssetWriter旋转缓冲区,ios,swift,avfoundation,avassetwriter,cmsamplebuffer,Ios,Swift,Avfoundation,Avassetwriter,Cmsamplebuffer,我正在使用AVFoundation在Swift中开发一个实时录制应用程序,我对视频定向有一个问题。我使用AVAssetWriter而不是AVCaptureMovieFileOutput,因为我需要以方形格式录制,如果我错了,请更正我 我尝试使用videoInput.transform,但听说并非所有视频播放器都支持它 我无法基于设备方向使用avcaptureconnection.videoOrientation,因为存在一些主UI线程停止 我了解到最好的解决方案是在AVCaptureVideoD

我正在使用AVFoundation在Swift中开发一个实时录制应用程序,我对视频定向有一个问题。我使用AVAssetWriter而不是AVCaptureMovieFileOutput,因为我需要以方形格式录制,如果我错了,请更正我

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

我无法基于设备方向使用avcaptureconnection.videoOrientation,因为存在一些主UI线程停止

我了解到最好的解决方案是在AVCaptureVideoDataOutputSampleBufferDelegate委托函数captureOutput中旋转CMSampleBuffer。。。。这看起来有点复杂,苹果的文档帮不了什么忙,很多帖子都是Objective-C

在这样做之前,我想知道是否有一些我可能错过的解决方案。 感谢您使用AVAssetWriter。试试看

然后像这样初始化AVAssetWriter

adaptor = AVAssetWriterInputPixelBufferAdaptor(rotationAngle: AVCaptureDevice.correctOrientation)
assetWriter = AVAssetWriter(input: adaptor.assetWriterInput)
为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
    }
为AvassetWriterInputPixelBufferAdapter创建另一个扩展

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