Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 it will stop the background music. I am developing on iOS using Swift. Here is a piece of the code that initiates the ingame sounds.

func playSpawnedDot() {     var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("spawnDot", ofType: "mp3")!)!     var error:NSError?     audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)     audioPlayer.prepareToPlay()      if volumeBool {         audioPlayer.play()     } } 
like image 332
Nathan Harper Avatar asked Mar 13 '15 03:03

Nathan Harper


People also ask

How do I play music in the background in iOS Swift?

Under the Capabilities tab, set the Background Modes switch to ON and select the “Audio, AirPlay, and Picture in Picture” option under the list of available modes. With this mode enabled and your audio session configured, your app is ready to play background audio.

How do you keep music playing while playing other apps?

From the Home screen, tap Apps > Music Player . Tap a song in your library to listen to it. Tap the Menu Key > Settings and checkmark the Show notification option so that the music controller is displayed on the Notifications panel.


1 Answers

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.

like image 80
lchamp Avatar answered Oct 13 '22 12:10

lchamp