Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background device music gets stopped as app starts ios

I am playing music in iphone and when I run my application it should not stop background device music and should stop its own music instead background music is getting stop. I want to do same as candy crush app. What should I do to resolve this? Please help me

    var isOtherAudioPlaying = AVAudioSession.sharedInstance().otherAudioPlaying
      println("isOtherAudioPlaying>>> \(isOtherAudioPlaying)")
      if(isOtherAudioPlaying == false)
           {
            audioPlayer1!.play()
           }
like image 841
Zalak Patel Avatar asked Jan 28 '15 14:01

Zalak Patel


3 Answers

I would suggest checking out Sameer's answer to this for Swift 2.0, just a few months back. Works perfectly with Swift 2.0.

let sess = AVAudioSession.sharedInstance()
if sess.otherAudioPlaying {
    _ = try? sess.setCategory(AVAudioSessionCategoryAmbient, withOptions: []) //
    _ = try? sess.setActive(true, withOptions: [])
}
like image 112
David West Avatar answered Oct 23 '22 20:10

David West


Since the default is AVAudioSessionCategorySoloAmbient, you need to set the proper category for your app and activate it. You could use AVAudioSessionCategoryAmbient for mixing audio.

Add this in your AppDelegate.swift:

func applicationDidBecomeActive(application: UIApplication) {
  AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
  AVAudioSession.sharedInstance().setActive(true, error: nil)
  // ...
}

Enjoy!

like image 36
Bogdan Stanca-Kaposta Avatar answered Oct 23 '22 22:10

Bogdan Stanca-Kaposta


Defer AVAudioSession.sharedInstance().setActive(true, error: nil) till when you need to start playing audio. Starting the session immediately after the app launches stops playback on other apps.

More details: https://developer.apple.com/documentation/avfoundation/avaudiosession

like image 33
Taiwosam Avatar answered Oct 23 '22 20:10

Taiwosam