参数介绍
//audioPath1 第一个音频路径
//audioPath2第二个音频路径
//outputPath合成之后的音频路径
+ (void)mixAudio:(NSString *)audioPath1 andAudio:(NSString *)audioPath2 toFile:(NSString *)outputPath
{
NSMutableArray *arrary = [[NSMutableArray alloc]init];
NSURL *url = [NSURL fileURLWithPath:audioPath1];
AVAsset *avset = [AVAsset assetWithURL:url];
NSURL *url1 = [NSURL fileURLWithPath:audioPath2];
AVAsset *avset1 = [AVAsset assetWithURL:url1];
[arrary addObject:avset];
[arrary addObject:avset1];
AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *soundtrackTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
CMTime insertTime = kCMTimeZero;
for(AVAsset *videoAsset in arrary)
{
[soundtrackTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:insertTime error:nil];
// Updating the insertTime for the next insert
insertTime = CMTimeAdd(insertTime, videoAsset.duration);
}
NSURL *outptVideoUrl = [NSURL fileURLWithPath:outputPath];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition presetName:AVAssetExportPresetAppleM4A];
// Setting attributes of the exporter
exporter.outputURL=outptVideoUrl;
exporter.outputFileType =@"com.apple.m4a-audio"; //AVFileTypeQuickTimeMovie;
exporter.shouldOptimizeForNetworkUse = YES;
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
//completion(exporter);
// [self exportDidFinish:exporter];
// [self exportDidFinish:exporter:assets];
NSLog(@"-----合并完成-----");
[[NSNotificationCenter defaultCenter]postNotificationName:@"success" object:nil];
});
}];
}
网友评论