问题
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()
}
回答1:
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!
回答2:
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: [])
}
回答3:
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
回答4:
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....
来源:https://stackoverflow.com/questions/28194514/background-device-music-gets-stopped-as-app-starts-ios