简体   繁体   中英

Separate Audio from Video

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);
    }
}];

Issue: get asset blank, so app crashes.

[[audio_Asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] [__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array';

The crash has described the issue, you are trying to access an array beyond it's bounds. change:

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

to:

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

Your main issue may be that loading an AVURLAsset might not immediately load all the tracks. You can wrap your method (after getting audio_Asset ) in the load method to have better guarantee:

NSString *tracksKey = @"tracks";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM