2

Hi I build a basic game with swift that has background music. The game has multiple image views. I have the music playing with with the code below. How do I stop the music if the user exits out of the app using the home button. as it is now the music continues to play even when the user presses the home button. The background music continues through out all image views which is what i want.

    func playBackgroundMusic(thesong: String) {
        let url = NSBundle.mainBundle().URLForResource(thesong, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(thesong)")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

    playBackgroundMusic("thesong.mp3")

2 Answers2

2

You can use an observer in your controller like this:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseSong:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)

And call this function when your controller detect when your app is running in background:

func pauseSong(notification : NSNotification) {
    backgroundMusicPlayer.pause()
}

Then, when your app is opened again, add another observer to play the song:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playSong:"), name:UIApplicationWillEnterForegroundNotification, object: nil)

Then call this function:

func playSong(notification : NSNotification) {
    backgroundMusicPlayer.play()
}

Hope it helps you ;)

Thomas
  • 1,289
  • 1
  • 17
  • 29
  • Hey Tomas thanks for that, it stops the music perfectly when the app enters the background. Just having a bit of trouble resuming the music when the app is opened again. should the music resume? –  Mar 10 '16 at 23:22
  • Add another observer for `UIApplicationWillEnterForegroundNotification` and resume the music – dan Mar 10 '16 at 23:23
  • You're right, you have to (re)play the song when your app is opened again.. Let me see – Thomas Mar 10 '16 at 23:24
1

You have to use this function in your controller:

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

    backgroundMusicPlayer.pause()
}
Thomas
  • 1,289
  • 1
  • 17
  • 29