4
votes

I am using the following code to play music on my MENU SKScene:

Under the SKScene I declare the music action:

class MENU: SKScene {
let action: SKAction = SKAction.playSoundFileNamed("gameMusic.wav", waitForCompletion: false)

And in the touches began method, I play my sound when a button is touched.

    self.runAction(action, withKey:"stopIce")

And under my didMoveToView: I have the following code to stop the music when the MENU scene loads.

    self.removeActionForKey("stopIce")

When I touch the button on the MENU SkScene and transit to my Level Scene, the music plays perfectly. However, when I transition back to the MENU Skene where the button was, the code does not stop the music?

self.removeActionForKey("stopIce")

I want to stop all sounds when you go back to the MENU Scene so that if the player touches the button to go to Level SKScene again, the music does not have 2 tracks playing at the same time. Thanks :)

2

2 Answers

8
votes

If you're able to target iOS 9, there's a marvellous solution for this: SKAudioNode. It lets you play music and stop it whenever you want, plus it automatically loops when it's attached to a node.

To try it out, make a property like this:

var backgroundMusic: SKAudioNode!

Then add this to didMoveToView():

backgroundMusic = SKAudioNode(fileNamed: "music.m4a")
addChild(backgroundMusic)

That's all it takes to start playing! When you want it to stop, use this:

backgroundMusic.runAction(SKAction.stop())
3
votes

The audio will continue to play until it is finished I believe, so what you need to do, is pause the SKNode that it is on. If the SKNode is a sprite that you do not want to pause, then just add a sub child to the sprite that is designed to just play audio, and pause the child node