@peter. .
-(BOOL)compositeVideo{
NSURL *curAudio = [[NSBundle mainBundle]URLForResource:@"a" withExtension:@".pcm"];
NSURL *curVideo = [[NSBundle mainBundle]URLForResource:@"v" withExtension:@".mp4"];
AVAsset *video = [AVAsset assetWithURL:curVideo];
AVAsset *audio = [AVAsset assetWithURL:curAudio];
AVAssetTrack *vTrack = [[video tracksWithMediaType:AVMediaTypeVideo] firstObject];
NSArray *arr = [audio tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack *aTrack = [arr firstObject];
AVMutableComposition *composition = [AVMutableComposition composition];
AVMutableCompositionTrack *visualTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:1];
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
NSError *error;
[visualTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, video.duration) ofTrack:vTrack atTime:kCMTimeZero error:&error];
if (error) {
NSLog(@"video composition failed! error:%@", error);
return NO;
}
[audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audio.duration) ofTrack:aTrack atTime:kCMTimeZero error:&error];
if (error) {
NSLog(@"audio composition failed! error:%@", error);
return NO;
}
AVAssetExportSession *exporter = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
exporter.outputURL = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"compositedVideo.mp4"]];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
exporter.outputFileType = AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^{
if (exporter.error) {
NSLog(@"exporter synthesization failed! error:%@", error);
[self.delegate compositeDidFinishAtURL:nil duration:-1];
}else{
[self.delegate compositeDidFinishAtURL:exporter.outputURL duration:CMTimeGetSeconds(video.duration)];
}
}];
return YES;
}