How to play sound clips in Swift

Sachinthana Weliwattage
3 min readJan 18, 2021

In this post you can find a way to easily add sound clips to your swift project. In this post, I use a seperate new swift file for the sound and I recommend you to follow the same approach. Then we can specify which sound to play and other sound features in it.

Step 1

First of all, you can create a new file by right clicking your project file and selecting New File as shown below.

Figure 1

Step 2

Select “Swift File” in IOS section (Figure 2) and click next.

Figure 2

Step 3

Give your file a preferred name (Like I have set “Sound”) and click next (Figure 3).

Figure 3

Step 4

This will be your new sound file and you can see it as “Sound.swift” and you can start using your sound file in your project.

Figure 4

Step 5

After creating the sound file, let’s making it usable. Let’s start by adding a variable in the “Sound.swift” file as audioPlayer. Make sure to import AVFoundation.

import AVFoundationvar audioPlayer: AVAudioPlayer?

Step 6

You need to create a “playSound” function as shown below.

The inputs of the function I have define include:

  • fileName = This will be the file name of the actual audio file
  • type = This will be the type of sound (E.g. mp3 file)
  • isRepeated = This boolean parameter defines whether the sound clip will be repeated or not. You can see below how I have set “numberOfLoops” attribute of the “AVAudioPlayer” based on this parameter.

An example of how this function is used will be shown in a later step.

func playSound(fileName: String, type: String, isRepeated: Bool) {    if let path = Bundle.main.path(forResource: fileName, ofType: type) {        do {            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))            if(isRepeated){                audioPlayer?.numberOfLoops = -1            }            audioPlayer?.play()        } catch {            print("ERROR: Could not find and play the sound file!")        }    }}

Now your Sound.swift file should look like below.

Figure 5

Step 7

Drag and placed your audio clip in to your project folder. Select the Destination, Added Folders, Add to target as Figure 6 and click Finish button. Then you can find your sound file on your project (as Figure 7)

Figure 6
Figure 7

Step 8

As the final Step, you can add sound to any swift code by simply using calling the “playSound” method we defined earlier in Step 6.

For example, I added the SampleSound.mp3 file in Step 7 and I want it to be repeatable, so I would be using the following method in my code. If you are using a one-time sound effect (E.g. a game won sound), make sure to set the “isRepeated” to false.

playSound(fileName: “SampleSound”, type: “mp3”, isRepeated: true)

Hope you learnt something, let me know your thoughts in comments.

Cheers!

--

--