LoginSignup
1
0

More than 5 years have passed since last update.

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

Posted at

環境

-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

参照

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0