How to record Audio in iOS Application;

Posted on Updated on

Hello dev mate;XcodeLogo
Hope you had a good weekend and refreshing Monday;

Today we’ll learn how to record audio in iOS application; Now a days, I’m working on an application where I need to record voice of user for some processing; I tried some framework classes from iOS sdk in a test project and here are my findings;

So lets start;


Priminarly we’ll use following classes and framework

AVFoundation.framwork
Provides set of APIs to record/play audio and video in iOS application;

AVAudioRecorder
Called an audio recorder, provides audio recording capability in your application.

AVAudioPlayer
An instance of the AVAudioPlayer class called an audio player, provides playback of audio data from a file or memory;

1. Project Creation and Setup

1. Open you Xcode and create new project .i.e. File -> New -> New Project or  press Command+Shift+N

2. Create Single View Application and provide suitable name; In my case, its AudioRecordingExample;

3. Select project location etc and save it; Your project should look like this

Screen Shot 2012-12-09 at 3.31.58 PM

4. Add required framework to your project .i.e. AVFoundation; For this select your project in Navigator, then select Target at right sight panel; Go to Build Phases, chose Linke Binary with Libraries; Press + button from botom and chose AVFoundation from list;

Screen Shot 2012-12-09 at 3.37.41 PM

After adding framework, you libraries should look like this;

Screen Shot 2012-12-09 at 3.38.01 PM

2. Interface Design

First open the ViewController.xib file and make your screen like this; I’m sure I don’t need to explain how to design it; (:

Screen Shot 2012-12-09 at 4.14.08 PM

3. Declaring Variable in .h file;

Open you ViewController.h file from Navigator and add the following code there;

Implement the following AVAudioRecorderDelegate and AVAudioPlayerDelegate in your  viewController;


@interface ViewController : UIViewController <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

Include AVFoundation.h in your import section;


#import <AVFoundation/AVFoundation.h>

Add the following two variables, and four UIButtons in your viewController;

    //for recording section
    AVAudioRecorder *audioRecorder;
    IBOutlet UIButton *recordingButton;
    IBOutlet UIButton *stopRecordingButton;
    //for playback section
    AVAudioPlayer *audioPlayer;
    IBOutlet UIButton *playButton;
    IBOutlet UIButton *stopPlayingButton;

The name of variables are enough to describe their usage in our program; Bind the outlets with respective buttons on xib file;

Now add following methods in your .h file

-(IBAction) recordAudio;
-(IBAction) stopRecording;
-(IBAction) playAudio;
-(IBAction) stopPlaying;

4. Your .m file, actual code

Add the following code in your viewDidLoad method

- (void)viewDidLoad {
      [super viewDidLoad];
      audioRecorder.delegate = self;
      audioPlayer.delegate = self;
      playButton.enabled = NO;
      stopPlayingButton.enabled = NO;
      NSArray *dirPaths;
      NSString *docsDir;
      dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      docsDir = [dirPaths objectAtIndex:0];
      NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];
      NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
      NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
                                     [NSNumber numberWithInt:16], AVEncoderBitRateKey,
                                     [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                     [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                     nil];
      NSError *error = nil;
      audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL
                                                  settings:recordSettings
                                                     error:&error];
      if (error){
           NSLog(@"error: %@", [error localizedDescription]);
      } else {
           [audioRecorder prepareToRecord];
      }
}

Now add the action methods, bind with each UIButton over screen;

-(IBAction) recordAudio{
    if (!audioRecorder.recording){
       playButton.enabled = NO;
       stopRecordingButton.enabled = YES;
       [audioRecorder record];
    }
}
//-------------------------------------------------------------------------------------------
-(IBAction)stopRecording{
     stopRecordingButton.enabled = NO;
     playButton.enabled = YES;
     recordingButton.enabled = YES;
     if (audioRecorder.recording){
         [audioRecorder stop];
     }
}
//-------------------------------------------------------------------------------------------
-(IBAction) stopPlaying{
     if (audioPlayer.playing) {
         [audioPlayer stop];
     }
}
//-------------------------------------------------------------------------------------------
-(IBAction) playAudio{
     if (!audioRecorder.recording){
         stopPlayingButton.enabled = YES;
         recordingButton.enabled = NO;
         NSError *error;
         audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url error:&error];
         audioPlayer.delegate = self;
         if (error)
             NSLog(@"Error: %@", [error localizedDescription]);
         else
             [audioPlayer play];
    }
}

You can also implement these delegate methods, though to keep the tutorial simple, I’m not using them wisely here;


-(void)audioPlayerDidFinishPlaying: (AVAudioPlayer *)player successfully:(BOOL)flag{
    recordingButton.enabled = YES;
    stopPlayingButton.enabled = NO;
}
//-------------------------------------------------------------------------------------------
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"Decode Error occurred");
}
//-------------------------------------------------------------------------------------------
-(void)audioRecorderDidFinishRecording: (AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"Audio Player has finished recording");
}
//-------------------------------------------------------------------------------------------
-(void)audioRecorderEncodeErrorDidOccur: (AVAudioRecorder *)recorder error:(NSError *)error{
    NSLog(@"Encode Error occurred");
}
//-------------------------------------------------------------------------------------------

And we are good to go now; Just run the code, tap Record in recording section and speak something in your microphone; Hit stop and press Play in playback section; You’ll hear yourself for sure;

The audio file has saved in /Document directory of your project, and you can get its content by following code, for further uses;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your_file_name>];
NSData *fileContents = [NSData dataWithContentsOfFile:filePath];

Thats it; You have done infact;

Now its time to look some new concepts; Back to code when we initialized our AVAudioRecorder instance, we provide it a dictionary of setting, as given below

NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
                                  [NSNumber numberWithInt:16], AVEncoderBitRateKey,
                                  [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                  [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error];

This dictionary is holding the different parameters for the audio we are going to capture and record; It inclues Bit rate, Sample rate, Number of channels etc; Let discuss them one by one in a concise way;

Bit Rate
Bitrate refers to the number of bits—or the amount of data—that are processed over a certain amount of time; In audio, this usually means kilobits per second; For example, if you have a song with bitrate of 256 kilobits per second, meaning there are 256 kilobits of data stored in every second of a song; Multiply the bitrate with length of your song and you’ll get the file size; The higher the bitrate of a track, the more space it will take up on your computer;

Audio Channel
A channel in audio is just one separate stream of audio information; Mono audio sources have one channel, Stereo sources have two (left and right), or in more simple words Mono is 1 audio channel (You hear the same sound in both ears) where as Stereo is 2 audio channels (Each headphone can hear a different sound)
Now a days, the normally 5.1 audio channel are being use, having five normal audio channels (Left, Center, Right, Left Surround, Right Surround)

Sample Rate
Sample rate is the number of samples of audio carried per second; In simple words it is a frequency of audio; Data equal to bit rate is passed to processor to generate sample rates (audio frequency); More sample rate means more frequency and hence more clear, smooth audio listening experience;
44.1 kHz is the sampling rate of audio CDs giving a 20 kHz maximum frequency; 20 kHz is the highest frequency generally audible by humans, so making 44.1 kHz the logical choice for most audio material.

Read the code again for initializing the AVAudioRecorder instance; Hope this time you’ll have better understanding;

Happy coding; (:

Flag Counter

Advertisements

4 thoughts on “How to record Audio in iOS Application;

    kaliyarajalu said:
    August 9, 2013 at 08:07

    Such a nice code… Thanks for Your great Help… keep post like advanced things with more explanations

    Sagar said:
    July 26, 2014 at 06:34

    Great tute, was just wondering how would we save audios permanently and display it in table view so one can go back to it later and play it? Thanks

      Ans responded:
      February 26, 2015 at 10:22

      Can you please elaborate your requirements bit more? How your screen look like, and how do you want to save audios in TableView?

    John E said:
    February 26, 2015 at 05:28

    Good web site you’ve got here.. It’s difficult to find high quality writing like yours these
    days. I honestly appreciate individuals like you!
    Take care!!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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