Advertisement
Guest User

Export

a guest
Nov 28th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.05 KB | None | 0 0
  1. func export(videos: [Video], overlay: UIImage?) {
  2.    let videoComposition = AVMutableVideoComposition()
  3.    videoComposition.frameDuration = CMTimeMake(1, 30)
  4.    videoComposition.renderSize = CGSize(width: 1080, height: 1080)
  5.    let composition = AVMutableComposition()
  6.  
  7.    var time: Double = 0
  8.  
  9.    let videoTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
  10.    let audioTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
  11.  
  12.    for video in videos {
  13.      let asset = AVAsset(url: video.url)
  14.      let videoAssetTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first
  15.      let audioAssetTrack = asset.tracks(withMediaType: AVMediaTypeAudio).first
  16.      let atTime = CMTime(seconds: time, preferredTimescale: 30)
  17.  
  18.      do {
  19.        if let videoAssetTrack = videoAssetTrack {
  20.          try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: videoAssetTrack, at: atTime)
  21.        }
  22.        if let audioAssetTrack = audioAssetTrack {
  23.          try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: audioAssetTrack, at: atTime)
  24.        }
  25.  
  26.      } catch( _) {
  27.        self.delegate?.cameraDidFinishExportingVideo(nil)
  28.        return
  29.      }
  30.  
  31.      time += asset.duration.seconds
  32.    }
  33.  
  34.    let outputURL = Utilities.getOutputUrl()
  35.    self.exporter = AVAssetExportSession(asset: composition,
  36.                                         presetName: AVAssetExportPresetHighestQuality)
  37.    if let exporter = self.exporter {
  38.      exporter.outputURL = outputURL
  39.      exporter.shouldOptimizeForNetworkUse = true
  40.      exporter.outputFileType = AVFileTypeMPEG4
  41.  
  42.      exporter.exportAsynchronously {
  43.        if exporter.status == .completed {
  44.          let video = Video(from: outputURL)
  45.          DispatchQueue.main.async {
  46.            self.delegate?.cameraDidFinishExportingVideo(video)
  47.          }
  48.        } else {
  49.          self.delegate?.cameraDidFinishExportingVideo(nil)
  50.        }
  51.      }
  52.    }
  53.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement