Switch audio tracks for AVURLAsset with multiple AVAssetTracks type audio

I have an AVURLAsset with several AVAssetTracks of type audio. I would like to be able to allow the user to switch between these various audio tracks by clicking on the button. It works to turn the volume of the 1st track on and off, but other tracks are not heard if the volume is set to 1.0.

Here is the code for adjusting the volume of the tracks (the sender is a UIButton with the tag set for the asset index in audioTracks).

AVURLAsset *asset = (AVURLAsset*)[[player currentItem] asset]; NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio]; NSMutableArray *allAudioParams = [NSMutableArray array]; int i = 0; NSLog(@"%@", audioTracks); for (AVAssetTrack *track in audioTracks) { AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters]; float volume = i == sender.tag ? 1.0 : 0.0; [audioInputParams setVolume:volume atTime:kCMTimeZero]; [audioInputParams setTrackID:[track trackID]]; [allAudioParams addObject:audioInputParams]; i++; } AVMutableAudioMix *audioZeroMix = [AVMutableAudioMix audioMix]; [audioZeroMix setInputParameters:allAudioParams]; [[player currentItem] setAudioMix:audioZeroMix]; 

Do I need to do something to turn on the desired track?

+6
source share
1 answer

Ok, the problem. This is not related to the above code, as it works fine. The problem was that AVAssetTracks for sound other than the first track were not included. To enable them, you had to recreate the asset using AVMutableComposition:

 NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"]; AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil]; AVMutableComposition *composition = [AVMutableComposition composition]; AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; NSError* error = NULL; [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0] atTime:kCMTimeZero error:&error]; NSArray *allAudio = [asset tracksWithMediaType:AVMediaTypeAudio]; for (int i=0; i < [allAudio count]; i++) { NSError* error = NULL; AVAssetTrack *audioAsset = (AVAssetTrack*)[allAudio objectAtIndex:i]; AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,asset.duration) ofTrack:audioAsset atTime:kCMTimeZero error:&error]; NSLog(@"Error : %@", error); } 
+4
source

Source: https://habr.com/ru/post/897174/


All Articles