简体   繁体   中英

How to stop music in a SpriteKit game from another class

I am stumped on how to access and change an AVAudioPlayer variable from one class to another class.

I have a class named Gamescene and it has:

 var backgroundMusicPlayer: AVAudioPlayer!

Further along in the code, I have

 func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(
        filename, withExtension: nil)
    if (url == nil) {
        println("Could not find file: \(filename)")
        return
    }

    var error: NSError? = nil
    backgroundMusicPlayer =
        AVAudioPlayer(contentsOfURL: url, error: &error)
    if backgroundMusicPlayer == nil {
        println("Could not create audio player: \(error!)")
        return
    }

    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()



}

I have not been able to figure out how to access the variable backgroundMusicPlayer from my main menu class. If I can access it, I believe backgroundMusicPlayer.stop() will do the trick.

You should consider stopping your music player in your GameScene when you transition from your GameScene class to your MainMenu class. You can start music up again from your MainMenu class.

If for whatever reason you do not wish to do that, look at using NSNotificationCenter to send a message between classes.

I got it to work by declaring a global variable and incrementing the global variable every-time the mute button was pushed. I then went back to the playBackgroundMusic function and added an if statement.

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(
        filename, withExtension: nil)
    if (url == nil) {
        println("Could not find file: \(filename)")
        return
    }

    var error: NSError? = nil
    backgroundMusicPlayer =
        AVAudioPlayer(contentsOfURL: url, error: &error)
    if backgroundMusicPlayer == nil {
        println("Could not create audio player: \(error!)")
        return
    }



    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()

    if soundCount % 2 == 1
    {
        backgroundMusicPlayer.stop()
    }


}

This works for now, but I am not sure how I will be able to keep the sound off even when a user shuts down an restarts the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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