My SKAudioNode stops when I transition to secondScene

135 Views Asked by At

I know this is meant to be fairly simple but I just can't figure it out! I have my song playing in the background in sceneOne. I then switch over to sceneTwo and the music completely stops. How can I make the background music continue? Below is my code.

//Music
Music = SKAudioNode(fileNamed: "Verm - Explode.mp3")
self.addChild(Music)

The code above is shown in sceneOne. Please tell me how to continue it into sceneTwo. Thanks everyone. :)

2

There are 2 best solutions below

0
On

You can try this code it might helps you to solve your issue

runAction(SKAction.waitForDuration(0.1), completion: {
        self.backgroundMusic = SKAudioNode(fileNamed: "main.mp3")
        self.backgroundMusic.autoplayLooped = true
        self.addChild(self.backgroundMusic)
    })
0
On

The first scene will be released when transitioning to scene two. And your sound node is a child of the first scene, it is released as well. The right approach is not to retain the sound node across scenes, but to use AVFoundation framework to play background music. This is also recommended by the SpriteKit documentation. Specifically, AVAudioPlayer is the class you will need. It's api is fairly simple, please check its documentation.