1

I'm creating my first app. I have an app with music playing in the background with the following code:

var backgroundMusicPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

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

    }

    playBackgroundMusic("Starship.wav")
}

So what should I do in order to stop/mute the background music when I switch to another ViewController? Should I do this my FirstViewController or SecondViewController?

Obviously, I don't want the sound to be off in the SecondViewController as I have other stuff that will be playing there.

Cai
  • 3,609
  • 2
  • 19
  • 39

1 Answers1

1

To mute sound I simply mute the volume.

backgroundMusicPlayer.volume = 0

and set it to normal if I want sound

backgroundMusicPlayer.volume = 1

If you just want to pause music you can call

backgroundMusicPlayer.pause()

To resume you call

 backgroundMusicPlayer.resume()

If you want to stop music and reset it to the beginning you say this

 backgroundMusicPlayer.stop()
 backgroundMusicPlayer.currentTime = 0        
 backgroundMusicPlayer.prepareToPlay()

Did you also consider putting your music into a singleton class so its easier to play music in your different viewControllers.

Not sure this is what you are looking for as your question is a bit vague.

crashoverride777
  • 10,581
  • 2
  • 32
  • 56
  • Totally what I looked for. Not sure what it means to put it in a singleton. I'm new to app making. To make more clear what I make. It's a music app, where in the menu it has to play background music, but once you move on to music "tab" there should be no background cause the possibility to start a music playlist will happen. hope it makes sense. But the answer you gave me, was very helpfull – Arsene Survie Mar 18 '16 at 13:01
  • Hey, you are welcome. A singleton basically means that you create a class that only exits once. So you can access the same class in multiple view controllers etc without having to put your music code all over the place. Music is a good example of where a singleton class is useful. To get a better idea you can check my gitHub helper. https://github.com/crashoverride777/Swift2-Music-Helper – crashoverride777 Mar 18 '16 at 16:14