In this short tutorial I'm going to show to you how to play music and sound within your iOS app.

The application I'm going to build will be able to do the following tasks:

  • Play music in background
  • Stop music in backround
  • Play a sound when requested by the user
  • Change the volume for the audio

Let's start

1. Open Xcode and create a new iOS Application project
2. Select the Single View template and click "next"

 

Single View template


3. Set the product name and the Class Prefix to "MyAudioTutorial"

 

4. Set the directory where you want to store your application project and then click on the create button

5. On the left panel, select the project item and go down to the Linked Framework and Libraries, as shown in the following picture

Class Prefix

6 click on the "+" button and add the AVFoundation.framework item

7 click again on the "+" button and add the AudioToolbox.framework item

8 Let's start designing our interface selecting the Main.storyboard file from the left panel, we will need 2 UIButtons. The first one to start/stop background music and the second one to play a sound. Then we will need a UILabel, titled "Set Volume Value:", a UISlider to select the new volume value and another UILabel to show the value selected by the slider. The final storyboard shall look like the following:

Screen Shot 2013-12-03 at 07.03.30


9. the properties for the UISlider shall lool like the following picture

Screen Shot 2013-12-03 at 09.22.00

10. Let's go write some code.
11. Select the MyAudioTutorialViewController.h file from the left panel.
First we have to add two imports just below the #import <UIKit/UIKit.h>, so add the following two lines:
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

12. Then, we have to add an IBOutlet for each element in the storyboard. (since we won't do any action and we won't receive any event from the "Set Volume Value:" UILabel, we won't need the related Outlet. Add the following few lines to the interface declaration:
    IBOutlet UIButton *startStopBackground;
    IBOutlet UIButton *playMyEffect;
    IBOutlet UILabel  *volumeLabel;
    IBOutlet UISlider *volumeSlider;

13. Then, we need some variables to store data during the execution. In the interface add the following declarations:
    SystemSoundID mySoundEffect;
    AVAudioPlayer *backgroundMusicPlayer;
    BOOL backIsStarted;

mySoundEffect will point to the sound to be played each time the user hits the "Play a sound effect" button.
The AVAudioPlayer will provide playback of audio data from a file.
backIsStarted will keep track of background music. It will be true if background is running and false otherwise.

14. Last we have to add some methods declarations, and the declarations of the properties (outside of the interface block). Add the following lines before the @end statement.

the final file will look like the following


 

//

//  MyAudioTutorialViewController.h

//  MyAudioTutorial

//

//  Created by xappsoftware on 03/12/13.

//  Copyright (c) 2013 xappsoftware. All rights reserved.

//

 

#import <UIKit/UIKit.h>

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

 

@interface MyAudioTutorialViewController : UIViewController

{

    IBOutlet UIButton *startStopBackground;

    IBOutlet UIButton *playMyEffect;

    IBOutlet UILabel  *volumeLabel;

    IBOutlet UISlider *volumeSlider;

    

    SystemSoundID mySoundEffect;

    AVAudioPlayer *backgroundMusicPlayer;

    BOOL backIsStarted;

}

-(IBAction)start_stop:(id)sender;

-(IBAction)setVolumeValue:(id)sender;

-(IBAction)playMyEffect:(id)sender;

 

@property (nonatomic, retain)AVAudioPlayer *backgroundMusicPlayer;

@property (nonatomic, retain)IBOutlet UIButton *startStopBackground;

@property (nonatomic, retain)IBOutlet UIButton *playMyEffect;

@property (nonatomic, retain)IBOutlet UILabel  *volumeLabel;

@property (nonatomic, retain)IBOutlet UISlider *volumeSlider;

@end

 

15. Select the MyAudioTutorialViewController.m file from the left panel (Xcode)
16. After the @implementation statement add the following line
@synthesize  backgroundMusicPlayer, startStopBackground, volumeLabel, volumeSlider, playMyEffect;


17. Now let's initialize our application, in the – (void)viewDidLoad method add the following code, after the [super viewDidLoad]; line :
    backIsStarted = false; // At beginning the background music is not playing
    
    /* Now we prepare the file to play as background */
    NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@”background-music-aac” ofType:@”caf”];
    NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
    NSError *error;
    backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    [backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [backgroundMusicPlayer setNumberOfLoops:-1];    // -1 means loop forever
    [volumeSlider setValue:[backgroundMusicPlayer volume]*10]; // set up the volume slider value
    [volumeLabel setText:[NSString stringWithFormat:@”%f”, [backgroundMusicPlayer volume]*10]];// set up the volume labe value
    
    /* Now we prepare the file to play as effect */
    NSString *mySoundEffectPath = [[NSBundle mainBundle] pathForResource:@”mysoundeffect” ofType:@”caf”];
    NSURL *mySoundEffectUrl = [NSURL fileURLWithPath:mySoundEffectPath];
    AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain(mySoundEffectUrl), &mySoundEffect); // create the system sound to play when the "Play sound effect" UIBUtton will be pushed


18. Before the @end statement add the following methods implementation:
-(IBAction)start_stop:(id)sender
{
    if (backIsStarted) { // If background music is playing we have to stop it and then we have to change the UIButton title to "Start…..".
        [backgroundMusicPlayer stop];
        [startStopBackground setTitle:@”Start background Music” forState:UIControlStateNormal];
    }
    else { // If background music is not playing we have to start it and then we have to change the UIButton title to "Stop…..".
        [backgroundMusicPlayer prepareToPlay];
        [backgroundMusicPlayer play];
        [startStopBackground setTitle:@”Stop background Music” forState:UIControlStateNormal];
    }
    backIsStarted = !backIsStarted; // self explaining statement

}

-(IBAction)setVolumeValue:(id)sender
{
    // when the value of the slider changes we have to change the volume
    [volumeLabel setText:[NSString stringWithFormat:@”%f”, [volumeSlider value]]];
    [backgroundMusicPlayer setVolume:[volumeSlider value]/10.0]; // really simple way to change the volume
}

-(IBAction)playMyEffect:(id)sender
{
    // when the user taps on the "Play sound effect" UIButton we have to play the sound effect
    // Just a line of code.
    AudioServicesPlaySystemSound(mySoundEffect);
}

the final file will be as follows:

//

//  MyAudioTutorialViewController.m

//  MyAudioTutorial

//

//  Created by Luigi D'Andrea on 03/12/13.

//  Copyright (c) 2013 xappsoftware. All rights reserved.

//

 

#import "MyAudioTutorialViewController.h"

 

@interface MyAudioTutorialViewController ()

 

@end

 

@implementation MyAudioTutorialViewController

@synthesize  backgroundMusicPlayer, startStopBackground, volumeLabel, volumeSlider, playMyEffect;

 

 

– (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    backIsStarted = false; // At beginning the background music is not playing

    

    /* Now we prepare the file to play as background */

    NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"background-music-aac" ofType:@"caf"];

    NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];

    NSError *error;

    backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];

    //[backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions

    [backgroundMusicPlayer setNumberOfLoops:-1];    // -1 means loop forever

    [volumeSlider setValue:[backgroundMusicPlayer volume]*10]; // set up the volume slider value

    [volumeLabel setText:[NSString stringWithFormat:@"%f", [backgroundMusicPlayer volume]*10]];// set up the volume labe value

    

    /* Now we prepare the file to play as effect */

    NSString *mySoundEffectPath = [[NSBundle mainBundle] pathForResource:@"soundEffect" ofType:@"caf"];

    NSURL *mySoundEffectUrl = [NSURL fileURLWithPath:mySoundEffectPath];

    AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain(mySoundEffectUrl), &mySoundEffect); // create the system sound to play when the "Play sound effect" UIBUtton will be pushed

}

 

 

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

-(IBAction)start_stop:(id)sender

{

    if (backIsStarted) { // If background music is playing we have to stop it and then we have to change the UIButton title to "Start…..".

        [backgroundMusicPlayer stop];

        [startStopBackground setTitle:@"Start background music" forState:UIControlStateNormal];

    }

    else { // If background music is not playing we have to start it and then we have to change the UIButton title to "Stop…..".

        [backgroundMusicPlayer prepareToPlay];

        [backgroundMusicPlayer play];

        [startStopBackground setTitle:@"Stop background music" forState:UIControlStateNormal];

    }

    backIsStarted = !backIsStarted; // self explaining statement

}

 

 

-(IBAction)setVolumeValue:(id)sender

{

    // when the value of the slider changes we have to change the volume

    [volumeLabel setText:[NSString stringWithFormat:@"%f", [volumeSlider value]]];

    [backgroundMusicPlayer setVolume:[volumeSlider value]/10.0]; // really simple way to change the volume

}

 

-(IBAction)playMyEffect:(id)sender

{

    // when the user taps on the "Play sound effect" UIButton we have to play the sound effect

    // Just a line of code.

    AudioServicesPlaySystemSound(mySoundEffect);

}

 

 

@end

19. Now let's go back to the Main.storyboard file, we have to do some connections.
  — Select My Audio Tutorial View Controller (yellow icon), right-click and drag to the "Start Background Music" UIButton, in the menu that will appear select the "startStopBackround" item. take a look at the following picture.

Screen Shot 2013-12-03 at 09.04.50
  — Select My Audio Tutorial View Controller, right-click and drag to the "Play a sound effect" UIButton, in the menu that will appear select the "playMyEffect" item.
  — Select My Audio Tutorial View Controller, right-click and drag to the "Volume Slider" UISlider, in the menu that will appear select the "volumeSlider" item.
  — Select My Audio Tutorial View Controller, right-click and drag to the "Volume Labe" UILabel, in the menu that will appear select the "volumeLabel" item.

20. Attach methods:
  — Select "Volume Slider" UISlider, right-click and drag to the My Audio Tutorial View Controller (yellow icon), in the menu that will appear select the "setVolumeValue:" item (in the events section).
  — Select "Play a sound effect" UIButton, right-click and drag to the My Audio Tutorial View Controller (yellow icon), in the menu that will appear select the "playMyEffect:" item.
  — Select "Start background music" UIButton, right-click and drag to the My Audio Tutorial View Controller (yellow icon), in the menu that will appear select the "start_stop:" item.

21 Now let's add two sound files, you can download from here : back & effect, drag and drop the two files into the project navigator. In the panel that will appear, make sure all the options are set as shown in the following picture:

Screen Shot 2013-12-03 at 09.16.51

22 Click Finish
23 Now Click the Play Button to run your app

 

Gg1