Adjusting the volume of a playing AVPlayer

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

Leave a Comment