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

2019-12-12  本文已影响0人  假如兔子失了尾

/**

*  获取视频中的音频

*

*  @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

上一篇下一篇

猜你喜欢

热点阅读