iOS tutorial: play sound

19 01 2013

AudioToolbox in iOS is suitable for playing short system sounds in apps (if you need another types of sounds read this). To play sound in iOS app with AudioToolbox you have to do the following:

1. Add AudioToolbox framework to your application

Click on your project, navigate to Targets -> Build Phases -> Link Binary With Libraries -> Click ‘+’ sign -> find AudioToolbox.framework

Adding AudioToolbox framework

Adding AudioToolbox framework

2. Import AudioToolbox.h in your header file

just add this import statement:

#import <AudioToolbox/AudioToolbox.h>

3. Add audio files to the project folder

Drag audio files to the project folder:

Add audio files

Add audio files

4. Add SystemSoundID iVar

In implementation file add variable in the @interface section at the beginning of file. You can add more variables if you need more audio files to be played.

@interface MyViewController (){
    SystemSoundID soundClick;

5. Initialize audio files

You can init files in various places. In my example I do it in viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    //find URL to audio file
    NSURL *clickSound   = [[NSBundle mainBundle] URLForResource: @"click" withExtension: @"wav"];
    //initialize SystemSounID variable with file URL
    AudioServicesCreateSystemSoundID (CFBridgingRetain(clickSound), &soundClick);

6. Play audio file

Audio is played with one line invocation. Put it anywhere, where you need to play sound.


7. Dispose system sound

Some clanup in viewDidUnload:

- (void)viewDidUnload {

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



One response

7 04 2014

Nice article!

I miss a feature to pause though. I’d like to make a list view with some sounds from an array. When you click the play icon, it will play, click again and it’ll pause.

Let me know if you’d like to write and article about it some time. I’d repay you with a bunch of licenses to my plugin:

Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: