Skip to content

Instantly share code, notes, and snippets.

@Moligaloo
Last active May 11, 2016 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Moligaloo/7b0de3722d8655a30c7abe8b7b21becc to your computer and use it in GitHub Desktop.
Save Moligaloo/7b0de3722d8655a30c7abe8b7b21becc to your computer and use it in GitHub Desktop.
Combine video clips in iOS using AVFoundation
-(void) composeVideoClips:(NSMutableArray<AVURLAsset *> *)videoClips
forComposition:(AVMutableComposition *)composition
mediaType:(NSString *)mediaType
{
AVMutableCompositionTrack * composedTrack =
[composition addMutableTrackWithMediaType:mediaType
preferredTrackID:kCMPersistentTrackID_Invalid];
CMTime time = kCMTimeZero;
for (AVURLAsset *videoClip in videoClips) {
[composedTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoClip.duration)
ofTrack:[videoClip tracksWithMediaType:mediaType].firstObject
atTime:time
error:nil];
time = CMTimeAdd(time, videoClip.duration);
}
}
-(void) combineVideoClipsWithPaths:(NSArray<NSString *> *)paths
resultPath:(NSString *)resultPath
completion:(void (^)())completion
{
NSMutableArray<AVURLAsset *> *videoClips = [NSMutableArray array];
for (NSString *path in paths) {
NSURL *url = [NSURL fileURLWithPath:path];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
[videoClips addObject:asset];
}
AVMutableComposition* composition = [AVMutableComposition composition];
[self composeVideoClips:videoClips forComposition:composition mediaType:AVMediaTypeVideo];
[self composeVideoClips:videoClips forComposition:composition mediaType:AVMediaTypeAudio];
NSURL *url = [[NSURL alloc] initFileURLWithPath:resultPath];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL = url;
exporter.outputFileType = AVFileTypeMPEG4;
exporter.shouldOptimizeForNetworkUse = YES;
[exporter exportAsynchronouslyWithCompletionHandler:^{
if (exporter.status == AVAssetExportSessionStatusCompleted && completion) {
completion();
}
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment