user18908963
user18908963

Reputation:

Playing background music with Sprite Kit

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.

Upvotes: 2

Views: 221

Answers (2)

Michael N
Michael N

Reputation: 563

You can also try using an SKAction to play music:

https://developer.apple.com/documentation/spritekit/skaction/1417664-playsoundfilenamed

It works but it’s a little buggy at the moment. Larger MP3 files seem to crash the game or application.

I have been using one AVPlayer singleton for background music (December 2023) just because it’s more reliable.

However, AVPlayer cannot work concurrently with iTunes or Apple Music, so ideally SKAction is the preferred method in future builds of SpriteKit.

Upvotes: 0

Swift Dev Journal
Swift Dev Journal

Reputation: 20088

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.

Upvotes: 2

Related Questions