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