美文网首页
iOS 音视频分离(导出视频中的音频)

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

作者: 假如兔子失了尾 | 来源:发表于2019-12-12 14:27 被阅读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

    相关文章

      网友评论

          本文标题:iOS 音视频分离(导出视频中的音频)

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