Tom Kincaid
Tom Kincaid

Reputation: 4975

Setting iOS MPMusicPlayerController volume relative to AVAudioPlayer

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

Upvotes: 1

Views: 1058

Answers (1)

Lbrt Ranin
Lbrt Ranin

Reputation: 26

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);
}

Upvotes: 1

Related Questions