How To Play Sounds – AVAudioPlayer Tutorial


In this AVAudioPlayer tutorial, we’re going to go through an example of playing a sound file that you’ve added to your Xcode project.

You’ll see that it’s actually a really simple task to accomplish!

Adding the framework to your project

The first thing we’ll need to do is to add the AVFoundation framework to the project.

In the General tab of your Xcode project properties, the frameworks and libraries section is all the way at the bottom. If you click the “+” icon, you’ll get a dialog and you can search for the AVFoundation Framework to add it.

AV Foundation Framework

Adding the sound file to your project

For this demo, we’re going to need a sample mp3 or wav sound file. You can find a short clip on the net or download the source code for this demo to use the sample MP3 that I used.

When you have a sound file, simply drag it into your Xcode project and it’ll add the file as a resource to your project.

A sound file in the file navigator

Importing the framework

In the class that you want to play a sound, you’re going to have to import the AVFoundation classes. At the top of the .M file, import the framework like this:

Creating and initializing the AVAudioPlayer object

In my demo, I’m going to play a sound in the ViewController class so I’m going to create an instance variable in ViewController.m to hold the AVAudioPlayer object:

Then in the viewDidLoad method, I’m going to create a new AVAudioPlayer object and initialize it with the path to the sound file like this:

In Lines 6-7, I’m constructing a string with the bundle’s resource path and the file name of the sound. Then I’m using that string to create a file NSURL which we’ll pass into the initialization method of our AVAudioPlayer.

In Line 10, we create a new AVAudioPlayer object and initialize it with the NSURL. Now it’s ready to be used in our other methods.

Playing the sound

Where ever you want to play the sound, simply call the play method of the AVAudioPlayer object!

The AVAudioPlayer class has other properties to control playback (such as the number of times to loop) as well as properties that give you information about the sound file (such as the duration).

Check out the Apple class reference document for more information!

You can get the Xcode project for the demo here.