iOS 音视频分离(导出视频中的音频)

最新文章地址:https://www.jianshu.com/p/169b0aefc9d9

/**

*  获取视频中的音频

*

*  @param videoUrl 视频的本地路径

*  @param newFile 导出音频的路径

*  @completionHandle 音频路径的回调

*/

+ (void)VideoManagerGetBackgroundMiusicWithVideoUrl:(NSURL*)videoUrlnewFile:(NSString*)newFilecompletion:(void(^)(NSString*data))completionHandle{

    AVURLAsset*videoAsset = [[AVURLAssetalloc]initWithURL:videoUrloptions:nil];;

    NSArray *keys = @[@"duration",@"tracks"];

    [videoAssetloadValuesAsynchronouslyForKeys:keys completionHandler:^{

        NSError*error =nil;

        AVKeyValueStatusstatus = [videoAssetstatusOfValueForKey:@"tracks"error:&error];

        if(status ==AVKeyValueStatusLoaded) {//数据加载完成

            AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];

            // 2 - Video track

            //Audio Recorder

            //创建一个轨道,类型是AVMediaTypeAudio

            AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

            //获取videoAsset中的音频,插入轨道

            [firstTrackinsertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];

            NSURL*url = [NSURLfileURLWithPath:newFile];

            AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetAppleM4A];//输出为M4A音频

            exporter.outputURL= url;

            exporter.outputFileType=@"com.apple.m4a-audio";//类型和输出类型一致

            exporter.shouldOptimizeForNetworkUse = YES;

            [exporterexportAsynchronouslyWithCompletionHandler:^{

                dispatch_async(dispatch_get_main_queue(), ^{

                    if(exporter.status==AVAssetExportSessionStatusCompleted) {

                        completionHandle(newFile);

                    }else{

                        NSLog(@"提取失败原因:%@",exporter.error);

                        completionHandle(nil);

                    }

                });

            }];

        }

    }];

}

Demo分享 https://github.com/LXHugh/AVSeparation

你可能感兴趣的:(iOS 音视频分离(导出视频中的音频))