Playing sound effects
Playing simple sounds is even easier. We will use SKAction
objects to play sounds on specific events, such as picking up a coin or starting the game.
Adding the coin sound effect to the Coin class
First, we will add a happy sound each time the player collects a coin. To add the coin sound effect, follow these steps:
Open
Coin.swift
and add a new property to theCoin
class to cache a coin sound action:Â Â Â Â Â Â Â let coinSound = Â Â Â Â Â Â SKAction.playSoundFileNamed("Sound/Coin.aif", Â Â Â Â Â Â waitForCompletion: false)
Locate the
collect
function and add the following line at the bottom of the function to play the sound:Â Â Â Â Â Â Â // Play the coin sound: Â Â Â Â Â Â self.run(coinSound)
That is all you need to do to play the coin sound every time the player collects a coin. You can run the project now to test it out if you like.
Tip
To avoid memory-based crashes, it is important to cache each playSoundFileNamed
action object and rerun the same object...