Swift 4: How to Play Sound In Your iOS Project

S

Playing sound is easier than you think! Follow this tutorial to learn how to play audio in your next iOS project using Swift and Xcode.

LanguageXcode
Swift 410.1

Note: I write Swift and Xcode tutorials for beginners with minimal pre-existing knowledge of the material. Too basic for you? Then skip right to the code or download the tutorial files and play with them.


Tutorial Files:

For beginners, I recommend downloading the template file and following along with the tutorial. The template includes the sound file already imported and the Main.storyboard and ViewController.swift files ready for you to edit. You can also download the completed project file, below.

Factoid: The sound file used for this project is a recording of my 5 year old son. This audio file is actually used in an app that I’ll be releasing shortly.

Advanced users, skip to final code in our ViewController.swift file.

Note: When using downloaded Xcode project files (from anywhere) you will need to update the Bundle Identifier and the Team used for the provisioning to your own information.

Step 1: Setting up the UIButton

Begin by downloading the Template Project, above, or by creating a new project.

To play an audio file we are going to be setting up an IBAction controlled by a UIButton. This isn’t the only way use the audio function. For example, you could attach it to a TapGestureRecognizer or when the ViewController first loads, or a myriad of other ways. For this example, we’ll focus on the UIButton.

Lets first add our UIButton to the visual editor. Adding a UIButton is pretty basic, but just in case, here’s the instructions:

  • First, head over to Main.storyboard and insert a UIButton by clicking on the “Library” toolbar button.
  • Search for Button and drag it onto the visual editor
  • Label the Button Play Sound
Adding a UIButton to the visual editor

Setup ViewController.swift

Ok, now lets go to our ViewController.swift file and setup our ViewController class.

  • First, import the AVFoundation class by typing import AVFoundation underneath import UIKit. This will give us access to the necessary protocols and methods to work with the audio file.
  • Next, inside your class, declare a new global variable called audioPlayer of type AVAudioPlayer. For the purposes of this tutorial we will make it a non-optional by placing an exclamation mark after the type declaration.

The beginning of our ViewController.swift file should now look like this. I highlighted the two lines you should have added.

Linking our UIButton

Now we are ready to give our Play Audio button some functionality. Head back to Main.storyboard. This time we are going to open the assistant editor by clicking the Assistant Editor button in the toolbar (it looks like to interlocking circles).

This should open the Main.storyboard file and the ViewController.swift file side by side. If it doesn’t, then click on the button above the file in the right side of the assistant editor that shows the path of the file being shown (see image, below). It should say Automatic. If Automatic isn’t available, then click on it and select Manual and find the ViewController.swift file and click on it.

How to change which file is displayed on the visual editor. Swift 4 Tutorial
Click here to change which file is shown in the visual editor

Set up the IBAction

Now let’s set up the IBAction.

  • To do this, select the Play Sound button. Then, while pressing control, drag from the Play Sound button to the bottom of the ViewController class in the assistant editor (but inside the final curly brace).

If done correctly you should see this options box popup:

Adding an IBAction. Swift 4 tutorial.
Adding an IBAction
  • Name this action playButtonPressed and make the type UIButton, as seen above.

Now you can turn off the assistant editor if you like (press the Standard Editor button in the toolbar) and head back over to our ViewController.swift file.

The Code (finally!)

Find the @IBAction func playButtonPressed(...) function that we just created. Go ahead and make sure you function matches mine, below, then I’ll explain what we are doing:

  • Here we will first create a soundURL constant that will look for the audio file in our project folder. You may put your audio file in a subfolder and it will still find it. In the demo project I put it in a folder named Audio. Make sure when you import your audio file you select to copy the file to your project and not create a reference to it.
  • You can change forResource: "AudioFile" to the name of your audio file (without the extension).
  • withExtension: "mp3" can be changed to match your file as well (eg. wav)
  • Then we set the audioPlayer global variable to the AVAudioPlayer class initialized with the URL of our sound file. Since this can cause errors, we do this with the try keyword and place it in a do/catch block to catch any errors.
  • Finally, we play the audio.

Final Code

Here’s the final, completed project file:

Here’s the final ViewController.swift file:

Wrapping Up

If you followed this tutorial, you should now be able to easily play audio in Swift 4. I hope this helped you accomplish something on your iOS project. Have questions, corrections, or improvements? Leave me a comment below!

About the author

Robert Kolts

I am a developer enthusiast. I learn new programing languages just for fun. My favorite development platforms are WordPress and iOS, though I tinker in many things. RedRock App Studio is my creative outlet from my real job. I grew up in Wisconsin and am a die-hard Green Bay Packers fan. I'm happily married and have six (that's not a typo) kids.

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

Recent Comments

Archives

Categories

Meta