skip to Main Content

I added radio functionality to my application recently.

I wanted it to play music even when it is in the background.

So I implemented this piece of code

  do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: [.duckOthers, .allowBluetooth])
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error as NSError {
            print(error)
        }

I got the app to play music when in the background now but the problem is that the app stops all other app’s sounds when launched.

For example when SoundCloud is playing music and when I launch my app Soundcloud stops the music.

What I want to achieve is to make my app play music when it is in the background and also allow other apps to play music when my app is not playing music.

How can I fix that issue?

Thanks

2

Answers


  1.         do {
            try AVAudioSession.sharedInstance().setCategory(.ambient)
            try AVAudioSession.sharedInstance().setActive(true)
            
        } catch { print(error) }
    

    Above code add in AppDelegate.swift files didFinishLaunchingwithOptions method. This will solve your problem

    Login or Signup to reply.
  2. To partially answer your question, you can allow your app to play audio while other apps are playing audio with the following configuration:

    do {
      try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
    } catch(let error) {
      print(error.localizedDescription)
    }
    

    .playback means the audio playing is central to the use of your app. So if you’re playing music, background sounds like white noise, etc. you probably are using playback mode. .mixWithOthers is ‘An option that indicates whether audio from this session mixes with audio from active sessions in other audio apps.’ – in other words allows your primary audio to mix with audio coming from other apps.

    The one thing I haven’t figured out – is why on the first launch of my app other background audio pauses. Subsequent launches seem to work fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search