iOS 中 如何从视频中提取音频?

.h文件
/**

提取视频中的音频

@param videoPath 视频路径
@param completionHandle 完成回调
*/

+(void)accessAudioFromVideo:(NSURL *)videoPath completion:(void (^)(NSURL *outputPath,BOOL isSucceed)) completionHandle;

.m文件
需要导入系统的#import
/**

提取视频中的音频

@param videoPath 视频路径
@param completionHandle 完成回调
*/

+(void)accessAudioFromVideo:(NSURL *)videoPath completion:(void (^)(NSURL *outputPath,BOOL isSucceed)) completionHandle{
   
     AVAsset *videoAsset = [AVAsset assetWithURL:videoPath];
    //1创建一个AVMutableComposition
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc]init];
    //2 创建一个轨道,类型为AVMediaTypeAudio
    AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    //获取videoPath的音频插入轨道
    [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    
    //4创建输出路径
    NSURL *outputURL = [self exporterPath:@"mp4"];
    
    //5创建输出对象
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:mixComposition presetName:AVAssetExportPresetAppleM4A];
    exporter.outputURL = outputURL ;
    exporter.outputFileType = AVFileTypeAppleM4A;
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        if (exporter.status == AVAssetExportSessionStatusCompleted) {
            NSURL *outputURL = exporter.outputURL;
            completionHandle(outputURL,YES);
        }else {
            NSLog(@"失败%@",exporter.error.description);
            completionHandle(outputURL,NO);
        }
    }];
    
}
//  输出路径
+ (NSURL *)exporterPath:(NSString *)filename{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"selfMusic%@.%@",str,filename];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths firstObject];
    //这个是录制视频时存储到本地的video
    NSString *path = [NSString stringWithFormat:@"%@/KSYShortVideoCache",docPath];
    //判断文件夹是否存在,不存在就创建
    //创建附件存储目录
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *outputFilePath = [path stringByAppendingPathComponent:fileName];
    return [NSURL fileURLWithPath:outputFilePath];
}

你可能感兴趣的:(iOS 中 如何从视频中提取音频?)