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()
}
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: [])
}
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With