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

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

    If you want to play an alert sound:

    public func playSound(withFileName fileName: String) {
    
        if let soundUrl = Bundle.main.url(forResource: fileName, withExtension: "wav") {
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with:[.duckOthers])
                try AVAudioSession.sharedInstance().setActive(true)
    
                var soundId: SystemSoundID = 0
    
                AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)
                AudioServicesAddSystemSoundCompletion(soundId, nil, nil, { (soundId, clientData) -> Void in
                    AudioServicesDisposeSystemSoundID(soundId)
                    do {
                        // This is to unduck others, make other playing sounds go back up in volume
                        try AVAudioSession.sharedInstance().setActive(false)
                    } catch {
                        DDLogWarn("Failed to set AVAudioSession to inactive. error=\(error)")
                    }
                }, nil)
    
                AudioServicesPlaySystemSound(soundId)
            } catch {
                DDLogWarn("Failed to create audio player. soundUrl=\(soundUrl) error=\(error)")
            }
        } else {
            DDLogWarn("Sound file not found in app bundle. fileName=\(fileName)")
        }
    }
    

    And if you want to play music:

    import AVFoundation

    var audioPlayer:AVAudioPlayer?
    
    public func playSound(withFileName fileName: String) {
    
        if let soundUrl = Bundle.main.url(forResource: fileName, withExtension: "wav") {
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with:[.duckOthers])
                try AVAudioSession.sharedInstance().setActive(true)
    
                let player = try AVAudioPlayer(contentsOf: soundUrl)
                player.delegate = self
                player.prepareToPlay()
                DDLogInfo("Playing sound. soundUrl=\(soundUrl)")
                player.play()
                // ensure the player does not get deleted while playing the sound
                self.audioPlayer = player
            } catch {
                DDLogWarn("Failed to create audio player. soundUrl=\(soundUrl) error=\(error)")
            }
        } else {
            DDLogWarn("Sound file not found in app bundle. fileName=\(fileName)")
        }
    }
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.audioPlayer?.stop()
        do {
            // This is to unduck others, make other playing sounds go back up in volume
            try AVAudioSession.sharedInstance().setActive(false)
        } catch {
            DDLogWarn("Failed to set AVAudioSession inactive. error=\(error)")
        }
    }
    

提交回复
热议问题