可以傳網(wǎng)絡(luò)連接進(jìn)行合成
/**
* 合并兩段音頻
*
* @param url 主音樂路徑
* @param accompanimentUrl 背景音樂路徑
* @param success 成功后回調(diào)
* @param failure 失敗后回調(diào)
*/
-(void)audio:(NSURL *)url AndAccompaniment:(NSURL *)accompanimentUrl isSuccess:(void (^)(NSString *outPath))success failure:(void (^)())failure{
//創(chuàng)建AVAsset
AVURLAsset *audioAsset = [AVURLAsset assetWithURL:url];
AVURLAsset *accompanimentAsset = [AVURLAsset assetWithURL:accompanimentUrl];
AVMutableComposition *compostion = [AVMutableComposition composition];
AVMutableCompositionTrack *audio = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
[audio insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *accompaniment = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
[accompaniment insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[accompanimentAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];//背景音頻長度耿币,以主音頻長度為準(zhǔn)audioAsset.duration
AVAssetExportSession *session = [[AVAssetExportSession alloc]initWithAsset:compostion presetName:AVAssetExportPresetAppleM4A];
//輸出路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *outPutFilePath = [NSString stringWithFormat:@"%@/audio.m4a",[paths lastObject]];
if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath])
{
[[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
}
session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
session.outputFileType = @"com.apple.m4a-audio";
session.shouldOptimizeForNetworkUse = YES;
[session exportAsynchronouslyWithCompletionHandler:^{
if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath])
{
// 成功調(diào)用
/*注意牙甫,此處如果處理UI需要回主線程*/
dispatch_async(dispatch_get_main_queue(), ^{
success(outPutFilePath);
});
}
else
{ //失敗調(diào)用
dispatch_async(dispatch_get_main_queue(), ^{
failure();
});
}
}];
}