如何提取media中的audio
我都快疯掉了 找了好久方法 看了api 但是还是搞定不了 ,代码如下
NSURL *mp4URL = [[NSBundle mainBundle] URLForResource:@"haha.mp4" withExtension:nil];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:mp4URL options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey]];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:1000];
CMTime duration = asset.duration;
Float64 durationSeconds = CMTimeGetSeconds(duration); //视频总秒数
//获取帧率
Float64 fps = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] nominalFrameRate];
Float64 totalFrames = durationSeconds * fps;
NSLog(@"FLOAT:%f",totalFrames);
// CMTimeValue intervalSeconds = duration.value / 10;
CMTime time;
NSMutableArray *times = [NSMutableArray array];
for (NSUInteger i = 0; i < totalFrames; i++) {
// CMTimeMake(a,b) a当前第几帧, b每秒钟多少帧.当前播放时间a/b
//
// CMTimeMakeWithSeconds(a,b) a当前时间,b每秒钟多少帧.
time = CMTimeMake(i, fps);
[times addObject:[NSValue valueWithCMTime:time]];
}
CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero, duration);
// <-------分离音频
AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration)
ofTrack:[[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
[audioTrack insertTimeRange:audioTimeRange ofTrack:([asset tracksWithMediaType:AVMediaTypeAudio].count > 0) ? [asset tracksWithMediaType:AVMediaTypeAudio].firstObject : nil atTime:kCMTimeZero error:nil];
//创建输出对象
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL= [NSURL URLWithString:[NSString stringWithFormat:@"%@/nima.mp4",kSplitImages]];
exporter.outputFileType = AVFileTypeMPEGLayer3;
// @"com.apple.quicktime-movie";
exporter.shouldOptimizeForNetworkUse = YES;
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self exportDidFinish:exporter];
});
}];
// <=---------
__block NSInteger count = 0;
[generator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef cgImage,
CMTime actualTime,
AVAssetImageGeneratorResult result,
NSError *error) {
if (cgImage) {
UIImage *image = [UIImage imageWithCGImage:cgImage];
[images addObject:image];
[UIImagePNGRepresentation(image) writeToFile:[NSString stringWithFormat:@"%@/%ld.png",kSplitImages,(long)count++] atomically:YES];
NSLog(@"IMGPATH:%@,%lu",kSplitImages,(unsigned long)images.count);
}
}];