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

后端 未结 11 836
误落风尘
误落风尘 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:44

    This is how I do it in Swift 3.0

    var songPlayer : AVAudioPlayer?         
    
    func SetUpSound() {
    
    
            if let path = Bundle.main.path(forResource: "TestSound", ofType: "wav") {
                let filePath = NSURL(fileURLWithPath:path)
                songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)
                songPlayer?.numberOfLoops = -1 //logic for infinite loop
                songPlayer?.prepareToPlay()
                songPlayer?.play()
            }
    
            let audioSession = AVAudioSession.sharedInstance()
            try!audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers) //Causes audio from other sessions to be ducked (reduced in volume) while audio from this session plays  
    }
    

    You can see more of AVAudioSessionCategoryOptions here: https://developer.apple.com/reference/avfoundation/avaudiosessioncategoryoptions

提交回复
热议问题