Question

I have an app that plays background music using MPMusicPlayerController and foreground sounds using AVAudioPlayer. I want to control the relative volume so that MPMusicPlayerController is much lower, but setting the volumne changes the overall system volume as if using the buttons on the side of the phone. Is there way to lower the volumne of MPMusicPlayerController without lowering the system volume?

MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
musicPlayer.volume = 0.1; // at this point the overall system volune has been set to 0.1
[musicPlayer setQueueWithItemCollection:collection];
[musicPlayer play];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
[player prepareToPlay];
[player setVolume: 1.0]; // I want this to be twice as loud as MPMusicPlayerController
[player play];
Was it helpful?

Solution

You need to learn how to "duck" the MPMusicPLayer. Try calling the method below before and after you play the AVAudioPlayer.

Basically, [self setAudioSessionWithDucking:YES] before and [self setAudioSessionWithDucking:NO] after.

- (void)setAudioSessionWithDucking:(BOOL)isDucking
{
     AudioSessionSetActive(NO);

    UInt32 overrideCategoryDefaultToSpeaker = 1;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (overrideCategoryDefaultToSpeaker), &overrideCategoryDefaultToSpeaker);

    UInt32 overrideCategoryMixWithOthers = 1;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof (overrideCategoryMixWithOthers), &overrideCategoryMixWithOthers);

    UInt32 value = isDucking;
    AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(value), &value);

    AudioSessionSetActive(YES);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top