0
votes

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

  • "Ring/Silent" switch is on ring: background music doesn't stop and it plays in-app sound together with background music (-> What I don't want)

  • "Ring/Silent" switch is on silent: background music doesn't stop and no in-app sounds are played (-> What I want)

Option 2 [AVAudioSessionCategorySoloAmbient]:

  • "Ring/Silent" switch is on ring: background music stops and it plays in-app sound (-> What I want)

  • "Ring/Silent" switch is on silent: background music stops, but no in-app sounds are played (-> What I want, it shouldn't stop background music)

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

  • "Ring/Silent" switch is on ring: background music stops and it plays in-app sound (-> What I want)

  • "Ring/Silent" switch is on silent: background music stops and it plays in-app sound (-> What I don't want)


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() .

1

1 Answers

2
votes

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.