Zalak Patel
Zalak Patel

Reputation: 1965

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()
           }

Upvotes: 7

Views: 6108

Answers (4)

Vatsal Shukla
Vatsal Shukla

Reputation: 1272

Xcode 10.3
Swift 4.2
Tested in iPhoneX (12.2), iPhone5s(11.0.3)

Functionality -> Play audio in silent mode + with other application audio.

Here is the code,

private func setupAudioSession() {
        //enable other applications music to play while quizView
        let options = AVAudioSession.CategoryOptions.mixWithOthers
        let mode = AVAudioSession.Mode.default
        let category = AVAudioSession.Category.playback
        try? AVAudioSession.sharedInstance().setCategory(category, mode: mode, options: options)
        //---------------------------------------------------------------------------------
        try? AVAudioSession.sharedInstance().setActive(true)
    }

I will suggest you to set this function in AppDelegate -> didFinishLaunchingWithOptions....

Upvotes: 0

Taiwosam
Taiwosam

Reputation: 559

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

Upvotes: 1

David West
David West

Reputation: 1590

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: [])
}

Upvotes: 2

Bogdan Stanca-Kaposta
Bogdan Stanca-Kaposta

Reputation: 93

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!

Upvotes: 1

Related Questions