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)
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)

Background Music / long running sound

For longer running sound, for example background music use the AVAudioPlayer class. This requires adding the AVFoundation framework to the application, and import in into the Swift file

  1. Add the AVFoundation Framework to the project by selecting the project itself, and scrolling to the bottom of the screen, click the '+' button under 'Linked Frameworks and Libraries' and start typing AVFoundation in the search box that appears. Select the framework and click 'Add'
  2. In the appropriate swift file (e.g. the scene) add a statement to import the framework as follows:
    import AVFoundation
  3. Create a variable in the class to hold the instance of AVAudioPlayer (it needs to persist so it can continue playing music) e.g.:
    private var audioPlayer = AVAudioPlayer()
  4. At some point before you want to play the audio, configure the audio player withe the file as follows:
    //locate the file in the app's bundle
    let filePath = NSBundle.mainBundle().pathForResource("Music", ofType: "mp3")
    //convert the file location into a URL (unwrap optional with ! as we know file exists)
    let fileURL = NSURL(fileURLWithPath: filePath!)
    //reinstantiate the audioPlayer with the file
    _ = try? audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
  5. If you need the audio to start very quickly, pre-load it with the following code:
  6. Finally, where you want to play the audio, call the play() method as follows:

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