How can I allow background music to continue playing while my app still plays its sounds while using Swift

后端 未结 11 868
误落风尘
误落风尘 2020-12-04 11:57

I created an app and I am attempting to allow the user to continue to listen to their music while playing my game, but whenever they hit \"play\" and the ingame sounds occur

11条回答
  •  情书的邮戳
    2020-12-04 12:42

    I didn't think that just setting the AVAudioSession to AVAudioSessionCategoryOptions.duckOthers would work, but it did. Here is my full code to help the rookies like myself.

    Swift 4 - Full Example:

    var audioPlayer = AVAudioPlayer()
    
    
    func playSound(sound: String){
        let path = Bundle.main.path(forResource: sound, ofType: nil)!
        let url = URL(fileURLWithPath: path)
    
        let audioSession = AVAudioSession.sharedInstance()
        try!audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers)
    
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.play()
        } catch {
            print("couldn't load the file")
        }
    }
    

    I still need to figure out setActive (I was looking at this blog post) but the audio stops ducking when I leave the app, so it works for my app.

提交回复
热议问题