将AVI视频转换为MP4视频(在iOS上播放)

时间:2019-05-02 03:36:55

标签: ios swift avfoundation avassetexportsession

我有一个由第三方库生成的视频文件,该文件正在录制来自远程摄像机的视频。这个API会以AVI格式@ 4fps生成一个视频文件,而我的示例为352x288px

我一直在尝试转换视频以便在iOS中播放。我了解到iOS仅支持有限范围的视频格式,并且我一直在尝试使一切正常。

我尝试使用以下基于iOS Convert AVI to MP4 Format programatically ...

的内容
import UIKit
import AVFoundation

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }

  @IBAction func convert(_ sender: Any) {
    makeItSo()
  }

  func makeItSo() {

    guard let inputUrl = Bundle.main.url(forResource: "DVR8-4580V, Channel 7", withExtension: "avi") else {
      print("Could not find video source")
      return
    }

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("MyVideo.mp4").absoluteString
    let outputURL = URL(fileURLWithPath: filePath)
    print("OutputURL = \(outputURL)")
    convertVideoToLowQuailty(withInputURL: inputUrl, outputURL: outputURL, handler: { exportSession in
      guard let exportSession = exportSession else {
        print("No export session")
        return
      }
      print("exportSession.status = \(exportSession.status)")
      if exportSession.status == .completed {
        // Video conversation completed
        print("Video converstion completed")
      } else {
        print("Error = \(exportSession.error)")
      }
    })
  }

  func convertVideoToLowQuailty(withInputURL inputURL: URL?, outputURL: URL?, handler: @escaping (AVAssetExportSession?) -> Void) {
    if let anURL = outputURL {
      try? FileManager.default.removeItem(at: anURL)
    }
    var asset: AVURLAsset? = nil
    if let anURL = inputURL {
      asset = AVURLAsset(url: anURL, options: nil)
    }
    var exportSession: AVAssetExportSession? = nil
    if let anAsset = asset {
      exportSession = AVAssetExportSession(asset: anAsset, presetName: AVAssetExportPresetPassthrough)
    }
    exportSession?.outputURL = outputURL
    exportSession?.outputFileType = .mp4
    exportSession?.exportAsynchronously(completionHandler: {
      handler(exportSession)
    })
  }

}

和其他几种变体,但是它们失败了。上面的代码失败,并显示:

Error = Optional(Error Domain=AVFoundationErrorDomain Code=-11822 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x283244bd0 {Error Domain=NSOSStatusErrorDomain Code=-16976 "(null)"}})

因此,我假设我没有为转换器提供正确的选项/建议,或者仅仅是AVFoundation不支持这种类型的操作。

下面是MediaInfo生成的信息

General
Complete name                            : /Users/swhitehead/Downloads/DVR8-4580V, Channel 8.avi
Format                                   : AVI
Format/Info                              : Audio Video Interleave
File size                                : 361 KiB
Duration                                 : 28s 500ms
Overall bit rate                         : 104 Kbps

Video
ID                                       : 0
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : Baseline@L2
Format settings                          : 1 Ref Frames
Format settings, CABAC                   : No
Format settings, ReFrames                : 1 frame
Format settings, GOP                     : M=1, N=4
Codec ID                                 : H264
Duration                                 : 28s 500ms
Bit rate                                 : 101 Kbps
Width                                    : 352 pixels
Height                                   : 288 pixels
Display aspect ratio                     : 1.222
Frame rate                               : 4.000 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Bits/(Pixel*Frame)                       : 0.249
Stream size                              : 351 KiB (97%)

问题

是否可以通过某种方式将这种类型的视频文件转换为可以由iOS播放的支持mp4格式?

nb:我很欣赏这个潜在的广泛问题,因为可能不存在简单的解决方案,但是即使有些建议或暗示也会让我发疯

1 个答案:

答案 0 :(得分:0)

使用不带“格式设置,GOP:M = 1,N = 4”的视频。

当我使用没有GOP格式设置的视频时,它可以成功导出。