Home > OS >  Playing background music with Sprite Kit
Playing background music with Sprite Kit

Time:07-09

I am new to Sprite Kit and currently developing my first Game. Now I want to add some background music (and maybe later some effects) to it and tried it with this piece of code:

func playBackgroundMusic() {
        // 1 - Create player
        let url = Bundle.main.url(forResource: "mySong", withExtension: "mp3")!
        let player = try! AVAudioPlayer(contentsOf: url)
        
        // 2 - Play sound
        player.play()
    }
   

But for some reason it doesn't work. I noticed that when I play music and then run the game, the music stops but I can't hear my game music.

CodePudding user response:

The player variable is local to the playBackgroundPlayer function. When you start playing the music, the function exits. When the function exits, player no longer exists. That would explain why the music stops.

The fix is to add a property for the AVAudioPlayer to the class or struct that contains the playBackgroundPlayer function. Create the AVAudioPlayer instance when you init the class or struct. Call the play function inside playBackgroundPlayer.

  • Related