Adding music with AVAudio

SpriteKit and Swift make it very easy to play sounds in our games. We can drag sound files into our project, just like image assets, and trigger playback with SKActionplaySoundFileNamed.

We can also use the AVAudio class from the AVFoundation framework for more precise audio control. We will use AVAudio to play our background music.

Adding sound assets to the game

Locate the Sound directory in the Assets folder and add it to your project by dragging and dropping it into the project navigator. Once you are done, you should see the Sound folder show up in your project, just like any other file.

Playing background music

First, we will add the background music. We want our music to play, regardless of which scene the player is ...

Get Swift Game Development - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.