美文网首页
多段音频合成

多段音频合成

作者: lizhi_boy | 来源:发表于2018-09-15 09:40 被阅读15次
/**
 音频合成

 @param paths 要合成音频的路径(NSURL)按照先后顺序
 @param outputFilePath 合成后输出的路径
 @param fileName 文件名称
 @param success 合成成功
 @param failure 合成失败
 */
-(void)voiceCompoundWithVoicePaths:(NSArray *)paths outPutFilePath:(NSString *)outputFilePath withFileName:(NSString *)fileName compoundSuccess:(void(^)(NSString *path))success failure:(void(^)(NSError* error))failure{
  
        // 音频合成
        AVMutableComposition *composition = [AVMutableComposition composition];
        AVMutableCompositionTrack *comTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        CMTime beginTime = kCMTimeZero;
        
        for (int i = 0; i < paths.count; i++) {
        NSURL *voiceUrl = paths[i];
        AVURLAsset *voiceSet = [[AVURLAsset alloc] initWithURL:voiceUrl options:nil];
        AVAssetTrack *voiceTrack = [[voiceSet tracksWithMediaType:AVMediaTypeAudio] firstObject];
            [comTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, voiceSet.duration) ofTrack:voiceTrack atTime:beginTime error:nil];
            beginTime = CMTimeAdd(beginTime, voiceSet.duration);
        }
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL judge = [fileManager fileExistsAtPath:outputFilePath];
        // 判断该路径下是否存在对应的文件
        if (!judge){
            [fileManager createDirectoryAtPath:outputFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        // 最终合成输出路径
        NSString *outPutFilePath = [outputFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.m4a",fileName]];
        // 添加合成路径
        NSURL *fileUrl = [NSURL fileURLWithPath:outPutFilePath];
        // 输出
        AVAssetExportSession *assetExport = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
        assetExport.outputFileType = AVFileTypeAppleM4A;
        assetExport.outputURL = fileUrl;
        // 优化
        assetExport.shouldOptimizeForNetworkUse = YES;
        [assetExport exportAsynchronouslyWithCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!assetExport.error) {
                    //合成成功
                    success(outPutFilePath);
                }else{
                    //合成失败
                    failure(assetExport.error);
                }
            });
        }];
    }

相关文章

网友评论

      本文标题:多段音频合成

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