Last active
May 11, 2016 09:31
-
-
Save Moligaloo/7b0de3722d8655a30c7abe8b7b21becc to your computer and use it in GitHub Desktop.
Combine video clips in iOS using AVFoundation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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