I see a lag in the display when trying to turn off the ambient music (eg Music player or Spotify) for a sound effect. I’m using AudioServicesPlaySystemSound to play the effect itself. I use the following to start the session and play music in the background.
[audioSession setCategory:AVAudioSessionCategoryAmbient error:nil];
Then I set the category to playback to stop the music to make way for my effect
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
and use the following to restart the music
[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
This feels stupidly hacky and the setCategory:AVAudioSessionCategoryPlayback produces a delay in the display as the volume dies.
What’s the correct way of muting background music?
Thanks, Steve
First of all, I’m not sure why you set the category to
AVAudioSessionCategoryPlayback. Unless you really need to continue playing your sound effect with the silent switch off/the phone locked you should probably pickAVAudioSessionCategorySoloAmbientinstead, which also mutes background sounds. Once you are done with playing your sound effect, you can switch back to ambiant.If playback is really what you need (because you have an alarm clock or something), you might consider switching to playback category right away, then set the
kAudioSessionProperty_OverrideCategoryMixWithOthersproperty so the background sound is still playing, then switch that one off if you want it muted but you should first really make sure playback category is really needed.Alternatively, did you consider just ducking the background sound instead of muting it? Maybe you can stay at the ambiant category and just set the
kAudioSessionProperty_OtherMixableAudioShouldDuckaudio session property when you are playing the effect (and reset it afterwards). That means the background sound is reduced in volume when you do your effect which may be more desirable depending on what your app is doing.Last but not least, I’ve never used
AudioServicesPlaySystemSoundand it may not work with mixing or ducking, so you might need to switch toAVAudioPlayer.