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.
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.
For beginners, I recommend downloading the template file and following along with the tutorial. The template includes the sound file already imported and the
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
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
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.storyboardand insert a
UIButtonby clicking on the “Library” toolbar button.
- Search for
Buttonand drag it onto the visual editor
- Label the Button
Ok, now lets go to our
ViewController.swift file and setup our
- First, import the AVFoundation class by typing
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
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 isn’t available, then click on it and select
Manual and find the
ViewController.swift file and click on it.
Set up the IBAction
Now let’s set up the
- To do this, select the
Play Soundbutton. Then, while pressing control, drag from the
Play Soundbutton to the bottom of the
ViewControllerclass in the assistant editor (but inside the final curly brace).
If done correctly you should see this options box popup:
- Name this action
playButtonPressedand 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
The Code (finally!)
@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
soundURLconstant 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.
- Then we set the
audioPlayerglobal variable to the
AVAudioPlayerclass initialized with the URL of our sound file. Since this can cause errors, we do this with the
trykeyword and place it in a
do/catchblock to catch any errors.
- If you are feeling extra nerdy, you can read more about error handling in Swift.
- Finally, we play the audio.
Here’s the final, completed project file:
Here’s the final
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!