从视频中分离音频

时间:2015-10-14 18:10:53

标签: ios avassetexportsession avurlasset

float sliderValue = 0.5;
NSURL *audio_url = [[NSBundle mainBundle] pathForResource:@“video_fileName” ofType:@"mp4"]];
AVURLAsset* audio_Asset = [[AVURLAsset alloc]initWithURL:audio_url options:nil];
AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];

NSString* formattedNumber = [NSString stringWithFormat:@"%.01f", sliderValue];
NSLog(@"formattedNumber %@",formattedNumber);
NSLog(@"formattedNumber %.01f",[formattedNumber floatValue]);

[audioInputParams setVolume:[formattedNumber floatValue] atTime:kCMTimeZero];
[audioInputParams setTrackID:[[[audio_Asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]  trackID]];
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = [NSArray arrayWithObject:audioInputParams];



AVAssetExportSession *exportSession=[AVAssetExportSession exportSessionWithAsset:audio_Asset presetName:AVAssetExportPresetAppleM4A];
exportSession.audioMix = audioMix;

exportSession.outputURL=[NSURL fileURLWithPath:audioPath];
exportSession.outputFileType=AVFileTypeAppleM4A;

[exportSession exportAsynchronouslyWithCompletionHandler:^{
    if (exportSession.status==AVAssetExportSessionStatusFailed) {
        NSLog(@"failed");
    }
    else {
        NSLog(@"AudioLocation : %@",audioPath);
    }
}];

问题:获取资产空白,因此应用崩溃。

  

[[audio_Asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]   [__NSArrayM objectAtIndex:]:索引0超出空数组的边界';

1 个答案:

答案 0 :(得分:0)

崩溃描述了这个问题,你试图访问一个超出它界限的数组。改变:

[audioInputParams setTrackID:[[[audio_Asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]  trackID]];

为:

NSArray * tracks = [audio_Asset tracksWithMediaType:AVMediaTypeAudio];
if([tracks count]) {
    [audioInputParams setTrackID:[[tracks firstObject]  trackID]];
}

您的主要问题可能是加载AVURLAsset可能无法立即加载所有曲目。您可以在load方法中包装您的方法(在获得audio_Asset之后)以获得更好的保证:

NSString *tracksKey = @"tracks";

[audio_Asset loadValuesAsynchronouslyForKeys:@[tracksKey] completionHandler:  ^{ 
// rest of the code here