首页 > 解决方案 > 将 AVI 视频转换为 MP4 视频(用于在 iOS 上播放)

问题描述

我有一个视频文件,它是由第三方库生成的,它正在从远程摄像机录制视频。此 API 生成 AVI 格式 @ 4fps 的视频文件,我的示例为 352x288px

我一直在尝试将视频转换为在 iOS 中播放。我了解 iOS 仅支持有限范围的视频格式,并且我一直在努力使任何工作。

我尝试使用以下内容,它基于iOS Convert AVI to MP4 Format programmatically ...

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 格式?

注意:我很欣赏这可能是一个广泛的问题,因为可能不存在简单的解决方案,但即使是一些建议或提示也会受到赞赏,因为它让我发疯

标签: iosswiftavfoundationavassetexportsession

解决方案


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

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


推荐阅读