iOS / Play audio when screen is locked but not when phone on silent mode

589 views Asked by At

I have developed a chat app and the problem is notifications can be heard even if phone is on silent mode (1). The thing is, I want notifications to be played when screen is locked (2). I checked all AVAudioSession categories, and it seems that you can have either one of the following:

  • Sounds disabled when phone on silent mode or screen locked;
  • Sounds enabled even when phone on silent mode or screen locked.

How can I get sounds disabled when phone on silent mode, but enabled when phone NOT on silent mode and screen is locked? Is it possible to tweak the AVAudioSession further, or (apparently cannot) easily detect silent mode programmatically?

1

There are 1 answers

0
Georges On

OK, I fixed it. The solution was to use AudioToolbox and System Sound Services. The behavior of AudioToolbox is what I was looking for, i.e. it always respects the ring/silent switch, however it can also play in the background or when the screen is locked.

Since I really wanted to use AVAudioPlayer, I first check the ring/silent switch by playing a short blank system sound (let us say half a second sound). If the completion callback is made within less than 0.15 seconds, I know that I am on silent mode. If not, I go on and play whatever sounds I have with AVAudioPlayer.