停止在第三个ViewController - Swift 4上播放音乐

时间:2018-06-06 18:45:54

标签: ios swift avfoundation

我的第一个ViewController上有一个简单的背景音乐循环,如下所示:

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()

    }
}

我想知道如何阻止这种循环背景音乐在另一个场景中播放,在我的情况下 - 用户选择静音按钮时的“用户设置”屏幕。

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

1 个答案:

答案 0 :(得分:2)

选项1

class Service {

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

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

然后使用

Service.shared.gmusic?.stop()

选项2

在CurrentVC中

 let settingsVc = //

 settingsVc.delegate = self

 present(settingsVc

//

 calss SettingsVC:UIViewController {

    var delegate:CurrentVC?

    func stop () {

     delegate?.gmusic.stop()

 }