Xcode
avfoundation
Swift
Swift3.0
Xcode8

avfoundationを使って動画をトリミング

環境

-swift3
-xcode8

補足

下記の実装では動画ファイルをトリミングするだけで音声ファイルはくっついてきません

実装

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) ")
      }
    }

    }
}

ソース

github

参照