iosswiftavfoundationavaudiosession

Play sound only when Ring/Silent switch is on ring


I'm working on an app with a piano keyboard. I want that the sound after key-pressing is only played, when "Ring/Silent" switch is on ring. Then it should stop background music from other apps . If the "Ring/Silent" switch is on silent, it shouldn't do anything and let the background music from other apps play (like Spotify).

What I tried (with Spotify as background music):

Option 1 [AVAudioSessionCategoryAmbient]:

Option 2 [AVAudioSessionCategorySoloAmbient]:

I think that Option 2 is the closest option I can get. The iPhone shouldn't stop background music when "Ring/Silent" switch is on silent and I'd be happy.

Option 3 [AVAudioSessionCategoryPlayback]:


My Code:

let NoteSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: currentNote.sound, ofType: "m4a")!)
do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    try AVAudioSession.sharedInstance().setActive(true)
    audioPlayer = try AVAudioPlayer(contentsOf: NoteSound as URL)
    audioPlayer.prepareToPlay()
    audioPlayer.play()
} catch {
    print("Problem in getting File")
}

In the code example I only changed .setCategory() .


Solution

  • There is no native API to check if the phone is on Silent or not, and you are discouraged from basing your app's functionality on such user choices (On low battery mode, Charging or not, ...).

    There is a hack to check whether the device is muted or not: Play a short sound of 0.5s minimum duration, and detect the time it took to play. For more details on this workaround, have a look here.