control music, avaudioplayer

I am trying to control background music in my app. when the first vc loads the music begins, the user can switch to the settings menu and toggle music on/off. the issue comes when they return to the initial vc, the music begins again. I can't think of a solid way to stop the music from starting again. Any assistance is appreciated.


//initial view controller

import UIKit

import AVFoundation


var musicPlayer = AVAudioPlayer()


class ViewController: UIViewController {


}

override func viewDidLoad() {

super.viewDidLoad()

do{

musicPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "hood", ofType: "mp3")!))

musicPlayer.prepareToPlay()

}

catch{

print(error)

}

musicPlayer.play()

}



//2nd vc, settings vc

import UIKit

import AVFoundation


class Settings_ViewController: UIViewController {

@IBAction func musicSwitch(_ sender: Any) {

if ((sender as AnyObject).isOn != true)

{

musicPlayer.stop()

}

where do you connect your audio player to the IBAction that stop() ?


to what do you connect musicSwitch ?

the action musicSwitch in the 2nd vc controls the start/stop. musicPlayer is a global variable declared in the intial vc.

control music, avaudioplayer
 
 
Q