How to Allow In-App Music Without Stopping External Playback in Your Swift iOS App

Deepankar Bhade /

2 min read--

I was building an app that has some instance where it plays some sound. Now if I am listening to some song in background and using the app it stops my spotiy music which is a very bad UX.

Here's the code I was using for playing the song.

func playSound() { if let path = Bundle.main.path(forResource: "countdown", ofType: "mp3") { do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) audioPlayer?.play() } catch { print("ERROR") } } }

To fix this you need correctly set up the category for the AVAudioSession. As per the Apple documentation there's multiple options you can set as categories.

In my case I wanted the app music to play along with the spotify music, so I went for the Ambient category.

Note

According the Apple documentation:

This category is also appropriate for “play-along” apps, such as a virtual piano that a user plays while the Music app is playing. When you use this category, audio from other apps mixes with your audio. Screen locking and the Silent switch (on iPhone, the Ring/Silent switch) silence your audio.

I modified my code it set AVAudioSession to .ambient category and then activate the audio session.

func playSound() { do {
try AVAudioSession.sharedInstance().setCategory(.ambient, options: [])
try AVAudioSession.sharedInstance().setActive(true)
if let path = Bundle.main.path(forResource: "countdown", ofType: "mp3") { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) audioPlayer?.play() } else { print("Audio file not found") } } catch { print("Error setting up audio session: \(error.localizedDescription)") } }

This got my in-app music to not interept any external app music.

Hope you found this useful, I am pretty new to swift and stumbled upon this problem so solved it and wrote a blog on it.


Read more: