背景音乐播放两次

时间:2016-04-07 16:02:11

标签: ios swift uiviewcontroller sprite-kit background-music

当视图加载到我的菜单(menuViewController)上时,背景音乐开始(可以工作)。然后,当我点击开始并进入我的游戏(GameViewController)并返回菜单(menuViewController)时,它开始播放两次。

这是我的viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    if x == false{
        setButtons()

        // 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.volume = 0.4
                myAudioPlayer.prepareToPlay()
                myAudioPlayer.play()
                myAudioPlayer.numberOfLoops = -1
            }catch{
                print("error")
            }
        }
    }
}

我尝试实例化menuViewController,然后使用该实例而不是自动创建一个新实例(我猜这不起作用)

这是我的GameViewController

@IBAction func goToMenu(sender: AnyObject) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("menuViewController")
    self.presentViewController(vc, animated: true, completion: nil)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if segue.identifier == "gameToMenu" {
        let destinationController = segue.destinationViewController as! menuViewController
            destinationController.x = true
    }

我也收到错误消息:

  

“警告:尝试在Ninja.GameViewController上显示Ninja.menuViewController:0x7fdad4cdbf20:0x7fdad1c1d7a0,其视图不在窗口层次结构中!”

0 个答案:

没有答案