Adjusting the volume of a playing AVPlayer

Solution 1:

You can change the volume while playing using the method described here:

http://developer.apple.com/library/ios/#qa/qa1716/_index.html

While the text of the article seems to suggest that it can only be used to mute the audio, you can actually set the volume to anything you like, and you can set it after the audio is playing. For example, assuming your instance of AVAsset is called "asset", your instance of AVPlayerItem is called "playerItem", and the volume you want to set is called "volume", the following code should do what you want:

NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];

NSMutableArray *allAudioParams = [NSMutableArray array];
for (AVAssetTrack *track in audioTracks) {
  AVMutableAudioMixInputParameters *audioInputParams = 
    [AVMutableAudioMixInputParameters audioMixInputParameters];
  [audioInputParams setVolume:volume atTime:kCMTimeZero];
  [audioInputParams setTrackID:[track trackID]];
  [allAudioParams addObject:audioInputParams];
}

AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters:allAudioParams];

[playerItem setAudioMix:audioMix];

Solution 2:

Have you tried just preparing an AVMutableAudioMix and setting it on the AVPlayerItem while it is still playing? You should be able to ask the AVPlayer for its currentItem, which can provide its tracks that the AVMutableAudioMixInputParameters for the AVMutableAudioMix should reference. The times that you supply for the mix are relative to when the mix is applied.

Solution 3:

- (IBAction)sliderAction:(id)sender {
NSLog(@"slider :%f ", self.mixerSlider.value);

NSArray *audioTracks = [self.videoHandler.videoAsset tracksWithMediaType:AVMediaTypeAudio];

// Mute all the audio tracks
NSMutableArray *allAudioParams = [NSMutableArray array];
for (AVAssetTrack *track in audioTracks) {
    AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
    [audioInputParams setVolume:self.mixerSlider.value atTime:kCMTimeZero];
    [audioInputParams setTrackID:[track trackID]];
    [allAudioParams addObject:audioInputParams];
}
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters:allAudioParams];

[[self.mPlayer currentItem] setAudioMix:audioMix]; }

This method is called by the slider value changed. And you can call it while the video is playing.

Solution 4:

Note that the AVMutableAudioMix-based method described in the original question (and several answers) only works with file-based assets, not streaming media.

This is detailed in a document written by Apple, here:

https://developer.apple.com/library/content/qa/qa1716/_index.html

When I attempted to do this with streaming audio I did not receive any tracks returned from AVAsset's tracks(withMediaType:) method (Swift).