Difference between revisions of "Recording Audio on iOS 7 with AVAudioRecorder"

From Techotopia
Jump to: navigation, search
(New page: <table border="0" cellspacing="0" width="100%"> <tr> <td width="20%">Previous<td align="center">[[iOS 7 App Development Essentials|Table of C...)
 
m (Text replacement - "<google>ADSDAQBOX_FLOW</google>" to "<htmlet>adsdaqbox_flow</htmlet>")
Line 28: Line 28:
  
 
Select the Main.storyboard file and, once loaded, drag Button objects from the Object Library window (View -> Utilities -> Show 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 78-1:
 
Select the Main.storyboard file and, once loaded, drag Button objects from the Object Library window (View -> Utilities -> Show 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 78-1:
<google>ADSDAQBOX_FLOW</google>
+
<htmlet>adsdaqbox_flow</htmlet>
  
 
[[Image:ios_7_audio_recording_app_ui.png|The user interface for an iOS 7 audio recording example]]
 
[[Image:ios_7_audio_recording_app_ui.png|The user interface for an iOS 7 audio recording example]]

Revision as of 18:07, 1 February 2016

PreviousTable of ContentsNext
Playing Audio on iOS 7 using AVAudioPlayerIntegrating Twitter and Facebook into iOS 7 Applications


<google>BUY_IOS7</google>


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


Contents


An Overview of the AVAudioRecorder Tutorial

The goal of this chapter is to create an iOS 7 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 iOS 7 using AVAudioPlayer.

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 or iPad iOS single view-based application named Record with a corresponding class prefix.


Designing the User Interface

Select the Main.storyboard file and, once loaded, drag Button objects from the Object Library window (View -> Utilities -> Show 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 78-1:

The user interface for an iOS 7 audio recording example

Figure 78-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 stopAudio.

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:

#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)stopAudio:(id)sender;

@end

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. <google>BUY_IOS7</google> 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:

- (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;

   AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord 
        error:nil];

  _audioRecorder = [[AVAudioRecorder alloc]
                  initWithURL:soundFileURL
                  settings:recordSettings
                  error:&error];

   if (error)
   {
           NSLog(@"error: %@", [error localizedDescription]);
   } else {
           [_audioRecorder prepareToRecord];
   }
}

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 audio session and an instance of the AVAudioRecorder class are 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:

- (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)stopAudio:(id)sender {
    _stopButton.enabled = NO;
    _playButton.enabled = YES;
    _recordButton.enabled = YES;

    if (_audioRecorder.recording)
    {
            [_audioRecorder stop];
    } else if (_audioPlayer.playing) {
            [_audioPlayer stop];
    }
}

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:

-(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");
}

Testing the Application

Follow the steps outlined in Testing Apps on iOS 7 Devices with Xcode 5 to configure the application for installation on an iOS device. Configure Xcode to install the application on the connected device and build and run the application by clicking on the Run button in the main toolbar. Once loaded onto the device, the operating system will seek permission to allow the app to record audio. Select “OK” and touch the Record button to record some sound. Touch the Stop button when the recording is completed and use the Play button to play back the audio.


<google>BUY_IOS7</google>



PreviousTable of ContentsNext
Playing Audio on iOS 7 using AVAudioPlayerIntegrating Twitter and Facebook into iOS 7 Applications