swift3sprite-kitskactionskaudionode

SpriteKit not playing audio file?


I have made a custom class, SoundNode, to handle the playing of audio files. For now, it only plays the default "A2.mp3"

class SoundNode : SKSpriteNode{
func playSound(){
    run(SKAction.playSoundFileNamed("A2", waitForCompletion: false))
    }
}

I then call the playSound method in my SKScene like so:

SoundNode().playSound()

But, the sound never plays?? I have made sure the file exists within my project and have also double checked the file name to make sure it is correct. What is the problem here?


Solution

  • SoundNode is a kind of node. Every node only works when it is in a scene. Just creating a SoundNode and calling playSound does not do anything because the node has not been added to the scene!

    To make this work, just add it to the scene:

    let node = SoundNode()
    self.addChild(node)
    node.playSound()
    

    Also, I suggest that SoundNode should not inherit SKSpriteNode because it is obviously not a sprite i.e. something that can be seen on screen. Just make it inherit SKNode.