iosswiftsprite-kitswift2background-music

How do you add background music to SpriteKit?


I tried doing this:

let soundFilePath = NSBundle.mainBundle().pathForResource("GL006_SNES_Victory_loop.aif", ofType: "GL006_SNES_Victory_loop.aif")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
let player = AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
player.numberOfLoops = -1 //infinite
player.play()

I put this code in the didMoveToView function, and I have import AVFoundation at the top of my code. I get the error: Call can throw, but it is not marked with 'try' and the error is not handled.

Thank you in advance!


Solution

  • (Xcode 8 and Swift 3)

    Using SpriteKit this is pretty simple. You create an SKAudioNote with a sound file and then you attach it to your Scene as a child. It will loop by default:

    override func didMove(to view: SKView) {
        let backgroundSound = SKAudioNode(fileNamed: "bg.mp3")
        self.addChild(backgroundSound)
    }
    

    If you want to stop the background music at some point you can use the build in methods:

        backgroundSound.run(SKAction.stop())
    

    Or maybe you want to play the sound again after stopping it:

        backgroundSound.run(SKAction.play())
    

    SpriteKit makes this really simple. I hope this helps you.