swift - 为什么我的 avfoundation swift3 不起作用

标签 swift xcode avfoundation

当您运行以下项目时,将在设备上生成编辑后的视频。我用音频文件尝试了以下实现并成功了。但是,如果您将它作为电影运行,则不会发出任何错误,但会生成电影并且不会进入目录 https://github.com/Ryosuke-Hujisawa/My_AVAssetExportSession_AVMutableComposition-2

我的项目中有一个模型。型号如下 https://github.com/justinlevi/AVAssetExportSession_AVMutableComposition

我在音频文件中成功了。音频在目录中处于修剪和编辑状态。我想编辑视频。虽然我可以编辑视频,但编辑了,没有出现错误,但结果目录中不存在。或者它以音频文件的状态存在于目录中,而不是作为动画生成。请帮助我。

import UIKit
import AVFoundation

class ViewController: UIViewController {

  var asset: AVAsset?

  @IBAction func exportBtnDidTap(_ sender: AnyObject) {

    guard let asset = asset else {
      return
    }

    createAudioFileFromAsset(asset)
  }


  override func viewDidLoad() {
    super.viewDidLoad()

    let videoAsset = AVURLAsset(url: Bundle.main.url(forResource: "sample", withExtension: "m4v")!)

    let comp = AVMutableComposition()

    let videoAssetSourceTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first! as AVAssetTrack


    let videoCompositionTrack = comp.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

    do {

        try videoCompositionTrack.insertTimeRange(
            CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(10, 600)),
            of: videoAssetSourceTrack,
            at: kCMTimeZero)

    }catch { print(error) }

    asset = comp
  }

  func deleteFile(_ filePath:URL) {
    guard FileManager.default.fileExists(atPath: filePath.path) else {
      return
    }

    do {
      try FileManager.default.removeItem(atPath: filePath.path)
    }catch{
      fatalError("Unable to delete file: \(error) : \(#function).")
    }
  }

  func createAudioFileFromAsset(_ asset: AVAsset){

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL

    let filePath = documentsDirectory.appendingPathComponent("rendered-audio.m4v")
    deleteFile(filePath)

    if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A){

      exportSession.canPerformMultiplePassesOverSourceMediaData = true
      exportSession.outputURL = filePath
      exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration)
      exportSession.outputFileType = AVFileTypeAppleM4A
      exportSession.exportAsynchronously {
        _ in
        print("finished: \(filePath) :  \(exportSession.status.rawValue) ")
      }
    }

  }
}

最佳答案

我可以使用下面的实现裁剪视频。还更新了github

import UIKit
import AVFoundation

class ViewController: UIViewController {

  var asset: AVAsset?

  @IBAction func exportBtnDidTap(_ sender: AnyObject) {

    guard let asset = asset else {
      return
    }

    createAudioFileFromAsset(asset)
  }


  override func viewDidLoad() {
    super.viewDidLoad()

    let videoAsset = AVURLAsset(url: Bundle.main.url(forResource: "sample", withExtension: "m4v")!)

    let comp = AVMutableComposition()

    let videoAssetSourceTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first! as AVAssetTrack


    let videoCompositionTrack = comp.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

    do {

        try videoCompositionTrack.insertTimeRange(
            CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(1, 600)),
            of: videoAssetSourceTrack,
            at: kCMTimeZero)

    }catch { print(error) }

    asset = comp
  }

  func deleteFile(_ filePath:URL) {
    guard FileManager.default.fileExists(atPath: filePath.path) else {
      return
    }

    do {
      try FileManager.default.removeItem(atPath: filePath.path)
    }catch{
      fatalError("Unable to delete file: \(error) : \(#function).")
    }
  }

  func createAudioFileFromAsset(_ asset: AVAsset){

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL

    let filePath = documentsDirectory.appendingPathComponent("rendered-audio.m4v")
    deleteFile(filePath)

    if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset640x480){

      exportSession.canPerformMultiplePassesOverSourceMediaData = true
      exportSession.outputURL = filePath
      exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration)
      exportSession.outputFileType = AVFileTypeQuickTimeMovie
      exportSession.exportAsynchronously {
        _ in
        print("finished: \(filePath) :  \(exportSession.status.rawValue) ")
      }
    }

  }
}

关于swift - 为什么我的 avfoundation swift3 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45094170/

相关文章:

iOS 重用表格单元格设计

ios - 使用PO命令调试

ios - AVAssetResourceLoader 支持的 AVURLAsset 播放仅通过 AirPlay 失败

ios - 无法让 MapView 放大当前位置 - SWIFT

c++ - Xcode 找不到 C++ 静态库

swift - 快速获取 TableView 单元格内 uiswitch 值更改的标签值

ios - 在两个 iOS 设备之间通过 bonjour 传输图像

swift - 如何在 Parse 中构建两个用户之间的相互关系?

swift - Xcode AFNetworking - Command/bin/sh with exit code 1

iOS - 混合两个音频文件