merging videos together (AVFoundation)

前端 未结 4 2126
心在旅途
心在旅途 2021-02-06 18:17

In my app, I\'m recording small videos and adding them into an NSMutableArray as AVAsset so that i keep record of what has been captured. when the user

4条回答
  •  天涯浪人
    2021-02-06 19:01

    Swift version

    func merge(arrayVideos:[AVAsset], completion:@escaping (_ exporter: AVAssetExportSession) -> ()) -> Void {
    
      let mainComposition = AVMutableComposition()
      let compositionVideoTrack = mainComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
      compositionVideoTrack?.preferredTransform = CGAffineTransform(rotationAngle: .pi / 2)
    
      let soundtrackTrack = mainComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
    
      var insertTime = kCMTimeZero
    
      for videoAsset in arrayVideos {
        try! compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: insertTime)
        try! soundtrackTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: insertTime)
    
        insertTime = CMTimeAdd(insertTime, videoAsset.duration)
      }
    
      let outputFileURL = URL(fileURLWithPath: NSTemporaryDirectory() + "merge.mp4")
    
      let fileManager = FileManager()
      fileManager.removeItemIfExisted(outputFileURL)
    
      let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)
    
      exporter?.outputURL = outputFileURL
      exporter?.outputFileType = AVFileType.mp4
      exporter?.shouldOptimizeForNetworkUse = true
    
      exporter?.exportAsynchronously {
        DispatchQueue.main.async {
          completion(exporter!)
        }
      }
    }
    

提交回复
热议问题