繁体   English   中英

如何使用AVAudioPlayer在游戏中为多个场景暂停背景音乐

[英]How to pause background music in game using AVAudioPlayer for multiple scenes

因此,我在GameViewController的背景中循环播放了背景音乐。 暂停音乐按钮在GameScene中可用,用户可以在其中将游戏音乐静音或取消静音。

我有两个全局变量:

var muteButton = SKSpriteNode(imageNamed: "pause")
var mute: Bool = false 

在我添加的GameScene中,事情按预期运行(触发了打印响应)。

class GameScene: SKScene{

    override func didMove(to view: SKView){
       ...
        muteButton.position = CGPoint(x: self.size.width*0.2, y: self.size.height*0.90)
        muteButton.name = "Mute Button"
        muteButton.zPosition = 10
        self.addChild(muteButton)
    }

   override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     for touch: AnyObject in touches{
        let pointOfTouch = touch.location(in: self)
        let nodeITapped = atPoint(pointOfTouch)

        if nodeITapped.name == "Mute Button"{
            if mute == false {
                print("music will now turn OFF")
                mute = true
            }
            else{
                print("music will now turn ON")
                mute = false
            }

         }
      }
   } 
}

我怀疑静音变量仅在GameViewController viewDidLoad中被调用一次,因此if语句仅被检查一次。 因为我有多种感觉,所有这些都需要音乐才能播放,所以放置backgroundAudio的最佳位置就在这里。 在我的GameViewController中:

class GameViewController: UIViewController{

    var backgroundAudio = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Background Audio plays throughout the game
        let filePath = Bundle.main.path(forResource: "Track1",ofType:"mp3")
        let audioNS_URL = NSURL(fileURLWithPath: filePath!)

        if mute == false{
            do{ backgroundAudio = try AVAudioPlayer(contentsOf: audioNS_URL as URL)}
            catch { return print("No Audio Found")}
            // audio will loop forever
            backgroundAudio.numberOfLoops = -1
            backgroundAudio.play()
        }
        else{
            backgroundAudio.pause()
        }
    }
}

GameViewController内部添加观察者:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(switchBackgroundAudio), name: NSNotification.Name.init("switchBackgroundAudio"), object: nil)
    //... other stuff here ...//
}

然后添加一个用于打开/关闭声音的功能:

@objc func switchBackgroundAudio() {
   if mute == false {
     backgroundAudio.play()
   } else {
     backgroundAudio.pause()
   }
} 

最后,只要您在GameScene触摸按钮,就可以启动一个事件:

if nodeITapped.name == "Mute Button"{
  //... stuff here ...//
  NotificationCenter.default.post(Notification(name: NSNotification.Name("switchBackgroundAudio")))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM