当我启动我的应用程序时,背景音乐开始播放。但是,当我按下开始并玩游戏(在另一个 View Controller 中)然后返回菜单(第一个 View Controller )时,歌曲再次开始播放,但同一首歌曲仍在播放(结果 = 同时听到两次)。很烦人。这是我的 viewDidLoad 函数(可能是我的问题所在)。有人可以帮助我(通过解释或提供代码)仅在第一次加载 View 时播放音乐吗?
override func viewDidLoad() {
super.viewDidLoad()
// get path of audio file
let myFilePathString = NSBundle.mainBundle().pathForResource("Background Music Loop (Free to Use)", ofType: "mp3")
if let myFilePathString = myFilePathString {
let myFilePathURL = NSURL(fileURLWithPath: myFilePathString)
do { try myAudioPlayer = AVAudioPlayer(contentsOfURL: myFilePathURL)
myAudioPlayer.play()
myAudioPlayer.numberOfLoops = -1
}catch{
print("error")
}
}
}
最佳答案
myAudioPlayer.play
将再次调用,因为 VC 再次运行 viewDidLoad()
方法。
我的想法:
声明一个变量
var x = false
下一步 - 为您的音频播放器设置播放条件。
if x == false { // your code here }
当从其他 VC 触发 Segue 时,尝试使用 prepareForSegue
方法。
第二个 ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "yourIdentifier" {
let destinationController = segue.destinationViewController as! // Controller Name here
destinationController.x = true
}
}
这会将 x 设置为 true 并且音乐不会再次播放。
关于ios - 我的背景音乐被播放了两次(同时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36438063/