Setting iOS MPMusicPlayerController volume relative to AVAudioPlayer

纵然是瞬间 提交于 2019-12-08 04:35:51

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/17055234/setting-ios-mpmusicplayercontroller-volume-relative-to-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!