iOS 提取视频中音频数据,背景音乐
/**
截取视频的背景音乐
*/
+ (void)dM_VideoManager_getBackgroundMiusicWithVideoUrl:(NSURL*)videoUrl newFile:(NSString*)newFile completion:(void(^)(NSString*data))completionHandle
{
AVURLAsset* videoAsset = [[AVURLAsset alloc] initWithURL:videoUrl options: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 = [DM_YCUtilsdm_getVideoUlrInFile: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{
[SVProgressHUD showErrorWithStatus:exporter.error.userInfo.description];
[SVProgressHUD dismissWithDelay:1.5];
completionHandle(nil);
NSLog(@"失败了,原因是:%@",exporter.error);
}
});
}];
}
}];
}