第三次停止播放音乐 ViewController - Swift 4
Stop playing music on third ViewController - Swift 4
我的第一个 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()
}
}
我想知道如何阻止这个循环背景音乐在另一个场景中播放,在我的例子中 - 当用户选择静音按钮时的 "User Settings" 屏幕。
bgmusic.stop() \ Wont work because the object 'bgmusic' is not instantiated in the new scene?
选项 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()
}
我的第一个 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()
}
}
我想知道如何阻止这个循环背景音乐在另一个场景中播放,在我的例子中 - 当用户选择静音按钮时的 "User Settings" 屏幕。
bgmusic.stop() \ Wont work because the object 'bgmusic' is not instantiated in the new scene?
选项 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()
}