在 viewDidLoad
的 mainmenuviewcontroller 中,我告诉它播放背景歌曲。问题是,当用户转到另一个 View 然后返回主菜单时,它会再次开始播放歌曲,并且两个副本重叠。我尝试将其放入 viewDidLoad
但它不起作用
if themePlayer.playing == false {
themePlayer.prepareToPlay()
themePlayer.play()
}
它只是忽略 if 条件并继续播放。我怎样才能解决这个问题?
最佳答案
-viewDidLoad
仅在 View 首次加载时运行。由于当您离开 mainmenuviewcontroller
时,您的播放器仍在播放歌曲,这表明 View Controller 永远不会被释放。尝试将 if 条件放入 -viewDidAppear
或 -viewWillAppear
方法中。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
if themePlayer == nil {
// Either it's the first time this view is loaded, or themePlayer was deallocated
let soundURL = NSBundle.mainBundle().URLForResource("pres song", withExtension: "mp3")
themePlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
themePlayer.numberOfLoops = -1
themePlayer.volume = 0.1
themePlayer.prepareToPlay()
themePlayer.play()
}
if themePlayer.playing == false {
themePlayer.prepareToPlay()
themePlayer.play()
}
}
如果将来对是否正在调用某些内容有疑问,请使用 breakpoints并逐步执行代码。
关于ios - AVAudioPlayer 正在播放加时 View 续。加载[ swift ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31413346/