Sound

Sound Effects

Playing sound with SpriteKit can be very simple. For sound effects (i.e. short clips, not music), we simply create an SKAction constant and then run the action, as follows:

let soundFX = SKAction.playSoundFileNamed("Bang.mp3", waitForCompletion: false)
run(soundFX)
Setting true for the waitForCompletion parameter will make the action last as long as the sound (i.e. any subsequent actions in a sequence would wait for the clip to finish)

Controllable audio

For audio we may want to stop and start, for example background music, we can create an SKAudioNode and add it to a scene. The code below gives an example of how it can be done:

let audioNode = SKAudioNode(fileNamed: "music.mp3")
//stop the audio moving with the sprite!
audioNode.isPositional = false
addChild(audioNode)
//stop the audio
audioNode.run(SKAction.stop())
//restart audio
audioNode.run(SKAction.play())
Be aware that the audio gets attached to the node, so by default, if the node moves the sounds will travel with it (i.e. it will adjust relative to the speakers or headphones being used)

A note on decoding of audio

iOS provides hardware assisted audio decoding for certain file formats, however this is limited to one stream at a time. It is therefore best to use mp3 or AAC format (in an .m4a file) compressed audio for the main background music (or ambiance) to save file space, and use uncompressed sounds for effects to minimise CPU load, so the game play is not affected.

The simplest way to is to use uncompressed WAV of AIFF format files (which will work), however Apple recommend that you use either linear PCM uncompressed or IMA4 (IMA/ADPCM) slightly compressed audio packaged in a CAF file. You can read more on the preferred audio formats in iOS here