When you look for a way to play audio in your iOS application you usually find code like this
player = try AVAudioPlayer(contentsOf: url) player.prepareToPlay() player.play()
While this code works and will play the given audio file it does not deal with all the nuances of audio playback.
Imagine the user is playing a podcast or music, do you want the sound in your app to stop that playback? Or play over it?
The key to correct audio playback is understanding
AVAudioSession categories. Let’s take it by example
Playing ambient sounds over existing audio
If you want to play an audio file in your application without affecting the existing music or podcast playback that might be going on you should use the
You use this category for example to play sound effects like the sound of a message being sent in a chat application where the sound is not that important and definitely not worth affecting other playback in iOS.
You set the category on the shared
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
and make it active
All the sounds you now play using
AVAudioPlayer will be played as ambient sounds.
Stopping existing audio to play your sound
If the audio file you want to play in your application is important, for example playing a received voice message in a chat application, you can stop existing audio that is playing on iOS.
You can achieve this by setting the category to
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) try AVAudioSession.sharedInstance().setActive(true)
Remember, setting a category makes it persist for all the consecutive audio playback until you set it to a different value.
When you play a sound now using
AVAudioPlayer it will stop the music or podcast the user might be listening to.
But what if you want the users music or podcast to continue after you play your sound?[Read More]