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

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

    You need to set the AVAudioSession category, with one of the following value: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/index.html (AVAudioSession Class Reference).

    The default value is set to AVAudioSessionCategorySoloAmbient. As you can read :

    [...] using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing, use the AVAudioSessionCategoryAmbient category instead.

    You have to change the category, before you play your sound. To do so :

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)
    

    You don't need to call those line each time you play the sound. You might want to do it only once.

提交回复
热议问题