美文网首页
iOS音频合成

iOS音频合成

作者: 笨鸟不飞飞 | 来源:发表于2017-01-11 19:54 被阅读0次

    可以传网络连接进行合成

    /**
     *  合并两段音频
     * 
     *  @param url              主音乐路径
     *  @param accompanimentUrl 背景音乐路径
     *  @param success          成功后回调
     *  @param failure          失败后回调
     */
    -(void)audio:(NSURL *)url AndAccompaniment:(NSURL *)accompanimentUrl isSuccess:(void (^)(NSString *outPath))success failure:(void (^)())failure{
        //创建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];//背景音频长度,以主音频长度为准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])
            {
                // 成功调用
             /*注意,此处如果处理UI需要回主线程*/
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(outPutFilePath);
                });
                
            }
            else
            {   //失败调用
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure();
                });
            }
        }];
    
    }
    

    相关文章

      网友评论

          本文标题:iOS音频合成

          本文链接:https://www.haomeiwen.com/subject/ggvrbttx.html