Search code examples
iosxcodeswiftbackground-music

Background Music Stop/Mute on iOS


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.


Solution

  • 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.