Objective-c – Adjusting the volume of a playing AVPlayer

ios4iphoneobjective c

The only method for getting a volume change on currently playing AVPlayer items is to follow this process;

  • Offload the currently playing AVPlayerItem's asset
  • Grab the current playback time for that AVPlayerItem
  • Load the asset into a new AVPlayerItem
  • Replace the current AVPlayerItem with the new one
  • Wait for the currentItem to change on the AVPlayer
  • Prepare your AudioMix and seek to previous playback time

Have I missed a basic principle somewhere or is it meant to be this convoluted to simply manage volume levels?

I cannot use an AVAudioPlayer because I need to load iTunes tracks into the player.

Best Answer

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