Changes

Jump to: navigation, search

Recording Audio on an iPhone with AVAudioRecorder (iOS 6)

10,550 bytes added, 13:09, 5 October 2012
New page: <table border="0" cellspacing="0" width="100%"> <tr> <td width="20%">Previous<td align="center">[[iPhone iOS 6 Development Essent...
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="20%">[[Playing Audio on an iPhone using AVAudioPlayer (iOS 6)|Previous]]<td align="center">[[iPhone iOS 6 Development Essentials|Table of Contents]]<td Width="20%" align="right">[[Integrating Twitter and Facebook into iPhone iOS 6 Applications|Next]]</td>
<tr>
<td width="20%">Playing Audio on an iPhone using AVAudioPlayer<td align="center"><td width="20%" align="right">Integrating Twitter and Facebook into iPhone iOS 6 Applications</td>
</table>
<hr>


<google>BUY_IOS6</google>


In addition to audio playback, the iOS AV Foundation framework provides the ability to record sound on the iPhone using the AVAudioRecorder class. This chapter will work step-by-step through a tutorial demonstrating the use of the AVAudioRecorder class to record audio.

== An Overview of the iPhone AVAudioRecorder Tutorial ==

The goal of this chapter is to create an iOS 6 iPhone application that will record and playback audio. It will do so by creating an instance of the AVAudioRecorder class and configuring it with a file to contain the audio and a range of settings dictating the quality and format of the audio. Playback of the recorded audio file will be performed using the AVAudioPlayer class which was covered in detail in the chapter entitled [[Playing Audio on an iPhone using AVAudioPlayer (iOS 6)]].

Audio recording and playback will be controlled by buttons in the user interface that are connected to action methods which, in turn, will make appropriate calls to the instance methods of the AVAudioRecorder and AVAudioPlayer objects respectively.

The view controller of the example application will also implement the AVAudioRecorderDelegate and AVAudioPlayerDelegate protocols and a number of corresponding delegate methods in order to receive notification of events relating to playback and recording.

== Creating the Recorder Project ==

Begin by launching Xcode and creating a new iPhone iOS single view-based application named Record with a corresponding class prefix with Storyboards and Automatic Reference Counting enabled.

Since the iOS 6 AVAudioRecorder class is part of the AV Foundation framework it will be necessary to add the framework to the project. This can be achieved by selecting the product target entry from the project navigator panel (the top item named Record) and clicking on the Build Phases tab in the main panel. In the Link Binary with Libraries section click on the ‘+’ button, select the AVFoundation.framework entry from the resulting panel and click on the Add button.

== Designing the User Interface ==

Select the MainStoryboard.storyboard file and, once loaded, drag Button objects from the Object Library window (''View -> Utilities -> Object Library'') and position them on the View window. Once placed in the view, modify the text on each button so that the user interface appears as illustrated in Figure 69-1:


[[Image:iphone_ios_6_record_ui.png|The User Interface for an iPhone iOS 6 Audio Recording example app]]

Figure 69-1


Select the “Record” button object in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the RecordViewController.h file. Ctrl-click on the Record button object and drag to a position just below the @interface line in the Assistant Editor. Release the line and, in the resulting connection dialog, establish an outlet connection named recordButton. Repeat these steps to establish outlet connections for the “Play” and “Stop” buttons named playButton and stopButton respectively.

Continuing to use the Assistant Editor, establish Action connections from the three buttons to methods named recordAudio, playAudio and stop.

Select the RecordViewController.h file and modify it to import <AVFoundation/AVFoundation.h>, declare adherence to delegate protocols and add properties to store references to AVAudioRecorder and AVAudioPlayer instances:

<pre>
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface RecordViewController : UIViewController
<AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@property (strong, nonatomic) AVAudioRecorder *audioRecorder;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) IBOutlet UIButton *recordButton;
@property (strong, nonatomic) IBOutlet UIButton *playButton;
@property (strong, nonatomic) IBOutlet UIButton *stopButton;
- (IBAction)recordAudio:(id)sender;
- (IBAction)playAudio:(id)sender;
- (IBAction)stop:(id)sender;

@end
</pre>

== Creating the AVAudioRecorder Instance ==

When the application is first launched, an instance of the AVAudioRecorder class needs to be created. This will be initialized with the URL of a file into which the recorded audio is to be saved. Also passed as an argument to the initialization method is an NSDictionary object indicating the settings for the recording such as bit rate, sample rate and audio quality. A full description of the settings available may be found in the appropriate Apple iOS reference materials.

As is often the case, a good location to initialize the AVAudioRecorder instance is the viewDidLoad method of the view controller located in the RecordViewController.m file. Select the file in the project navigator, locate this method and modify it so that it reads as follows:

<pre>
- (void)viewDidLoad {
[super viewDidLoad];
_playButton.enabled = NO;
_stopButton.enabled = NO;

NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[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];
}
}
</pre>

Since no audio has yet been recorded, the above method disables the play and stop buttons. It then identifies the application’s documents directory and constructs a URL to a file in that location named sound.caf. An NSDictionary object is then created containing the recording quality settings before an instance of the AVAudioRecorder class is created. Assuming no errors are encountered, the audioRecorder instance is prepared to begin recording when requested to do so by the user.

== Implementing the Action Methods ==

The next step is to implement the action methods connected to the three button objects. Select the RecordViewController.m file and modify it as outlined in the following code excerpt:

<pre>
- (IBAction)recordAudio:(id)sender {
if (!_audioRecorder.recording)
{
_playButton.enabled = NO;
_stopButton.enabled = YES;
[_audioRecorder record];
}
}

- (IBAction)playAudio:(id)sender {
if (!_audioRecorder.recording)
{
_stopButton.enabled = YES;
_recordButton.enabled = NO;

NSError *error;

_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:_audioRecorder.url
error:&error];

_audioPlayer.delegate = self;

if (error)
NSLog(@"Error: %@",
[error localizedDescription]);
else
[_audioPlayer play];
}
}

- (IBAction)stop:(id)sender {
_stopButton.enabled = NO;
_playButton.enabled = YES;
_recordButton.enabled = YES;

if (_audioRecorder.recording)
{
[_audioRecorder stop];
} else if (_audioPlayer.playing) {
[_audioPlayer stop];
}
}
</pre>

Each of the above methods performs the step necessary to enable and disable appropriate buttons in the user interface and to interact with the AVAudioRecorder and AVAudioPlayer object instances to record or play back audio.

== Implementing the Delegate Methods ==

In order to receive notification about the success or otherwise of recording or playback it is necessary to implement some delegate methods. For the purposes of this tutorial we will need to implement the methods to indicate errors have occurred and also when playback finished. Once again, edit the recordViewController.m file and add these methods as follows:

<pre>
-(void)audioPlayerDidFinishPlaying:
(AVAudioPlayer *)player successfully:(BOOL)flag
{
_recordButton.enabled = YES;
_stopButton.enabled = NO;
}

-(void)audioPlayerDecodeErrorDidOccur:
(AVAudioPlayer *)player
error:(NSError *)error
{
NSLog(@"Decode Error occurred");
}

-(void)audioRecorderDidFinishRecording:
(AVAudioRecorder *)recorder
successfully:(BOOL)flag
{
}

-(void)audioRecorderEncodeErrorDidOccur:
(AVAudioRecorder *)recorder
error:(NSError *)error
{
NSLog(@"Encode Error occurred");
}
</pre>

== Testing the Application ==

Follow the steps outlined in Testing iOS 6 Apps on the iPhone – Developer Certificates and Provisioning Profiles to configure the application for installation on an iPhone device. Configure Xcode to install the application on the connected iPhone device and build and run the application by clicking on the Run button in the main toolbar. Once loaded onto the device, touch the Record button and record some sound. Touch the Stop button when the recording is completed and use the Play button to play back the audio.


<google>BUY_IOS6</google>


<hr>
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="20%">[[Playing Audio on an iPhone using AVAudioPlayer (iOS 6)|Previous]]<td align="center">[[iPhone iOS 6 Development Essentials|Table of Contents]]<td Width="20%" align="right">[[Integrating Twitter and Facebook into iPhone iOS 6 Applications|Next]]</td>
<tr>
<td width="20%">Playing Audio on an iPhone using AVAudioPlayer<td align="center"><td width="20%" align="right">Integrating Twitter and Facebook into iPhone iOS 6 Applications</td>
</table>

Navigation menu