Brewski
Brewski

Reputation: 684

Stop playing music on third ViewController - Swift 4

I have a simple background music loop on my first ViewController that looks like this:

func setupMusic() {

    if audioEnabled == true {

        let soundFile = Bundle.main.path(forResource: "bgMusic", ofType: ".wav")

        do {
            try bgmusic = AVAudioPlayer (contentsOf: URL(fileURLWithPath: soundFile!))
        }  catch {
            print (error)
        }

        bgmusic.numberOfLoops = -1
        bgmusic.volume = 0.3
        bgmusic.play()

    }
}

I would like to know how I stop this looping background music from playing in another scene, in my case - the "User Settings" screen when the user selects the mute button.

bgmusic.stop() \\ Wont work because the object 'bgmusic' is not instantiated in the new scene?

Upvotes: 1

Views: 166

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Option 1

class Service {

   static let shared = Service()
    var gmusic :AVAudioPlayer?
}

try Service.shared.gmusic = AVAudioPlayer (contentsOf: URL(fileURLWithPath: soundFile!))

then use

Service.shared.gmusic?.stop()

Option 2

in CurrentVC

 let settingsVc = //

 settingsVc.delegate = self

 present(settingsVc

//

 calss SettingsVC:UIViewController {

    var delegate:CurrentVC?

    func stop () {

     delegate?.gmusic.stop()

 }

Upvotes: 2

Related Questions