Search This Blog

Thursday 3 May 2012

code to record audio in iPhone

Hello friends,

I am quite new to iPhone technology but since I have started learning, I think its great fun. This is my first post so I would like to share something really interesting.

In this post I will explain you how to write a code to record audio and then play it.

First of all create a view based application in Xcode named AudioPlayer and then in AudioPlayerViewController.h write the following lines:

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

@interface AudioPlayerViewController : UIViewController<AVAudioRecorderDelegate,
AVAudioPlayerDelegate> {

   
    AVAudioRecorder *audioRecorder;
    AVAudioPlayer *audioPlayer;
    int recordEncoding;
    enum  {
        ENC_AAC = 1,
        ENC_ALAC = 2,
        ENC_IMA4 = 3,
        ENC_ILBC = 4,
        ENC_ULAW = 5,
        ENC_PCM = 6,
    }encodingTypes;
   
    IBOutlet UISlider *volume;
    IBOutlet UILabel *amountOfVolume;
}
@property (nonatomic, retain) UISlider *volume;
@property (nonatomic, retain) UILabel *amountOfVolume;

-(IBAction) startRecording;
-(IBAction) stopRecording;

-(IBAction) startPlaying;
-(IBAction) stopPlaying;
@end


Now open AudioPlayerViewController.xib in the bottom part add 4 buttons and connect the "Touch Up Inside" event with the above actions.

Now open AudioPlayerViewController.m file and add the code block given below.

#import "AudioPlayerViewController.h"

@implementation AudioPlayerViewController
@synthesize volume, amountOfVolume;

-(void)viewDidLoad{
    //may be the file type supported will be ENC_PCM
    recordEncoding = ENC_PCM;
    [super viewDidLoad];
}

-(IBAction) startRecording{
    NSLog(@"start recording");
   
    if(audioRecorder){
        [audioRecorder release];
        audioRecorder = nil;
    }
   
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryRecord error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
  
    NSMutableDictionary *recordSettings =
    [[NSMutableDictionary alloc] init];

    NSNumber *formatObject;
    // following are the conditions for checking encoding scheme used
    if (recordEncoding == ENC_PCM) {
               
        [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
       
    }
    else {
       
        switch (recordEncoding) {
            case (ENC_AAC):
                formatObject = [NSNumber numberWithInt:kAudioFormatMPEG4AAC];
                break;
            case (ENC_ALAC):
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleLossless];
                break;
            case (ENC_IMA4):
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
                break;
            case (ENC_ILBC):
                formatObject = [NSNumber numberWithInt:kAudioFormatiLBC];
                break;
            case (ENC_ULAW):
                formatObject = [NSNumber numberWithInt:kAudioFormatULaw];
                break;
            default:
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
                break;
        }
       
        [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
        [recordSettings setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    }
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [paths objectAtIndex:0];

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf",documentDir]];
    NSError *error = nil;
    audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];

    // if instance of audio record is not created followoing if condition is fired
    if(!audioRecorder){
        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: [err localizedDescription]
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
        [alert release];

        return;
    }

    [audioRecorder setDelegate:self];

    if ([audioRecorder prepareToRecord]) {
        [audioRecorder record];
        audioRecorder.meteringEnabled = YES;

    }
    else {
        int errorCode = CFSwapInt32HostToBig([error code]);
        NSLog(@"Error: %@[%4.4s]", [error localizedDescription], (char*)&errorCode);
    }
   
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        // this condition checks whether audio recording device is available or not

    }
   
    // start recording
    [audioRecorder recordForDuration:(NSTimeInterval) 10];

}

-(IBAction) stopRecording{
    NSLog(@"stop recording");
    [audioRecorder stop];
    NSLog(@"stop");
}

-(IBAction) startPlaying{
    NSLog(@"start playing");
    [audioPlayer release];
    audioPlayer = nil;
   
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

/* if you are testing in device the file cannot be saved in the main bundle. so it should be saved in documentdirectory*/
    NSString *documentDir = [paths objectAtIndex:0];

 
 

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf",documentDir]];
       
    NSError *error = nil;
   
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer play];


    //audioPlayer.volume = 100.0;
    // you can also change the volume according to the value of slider
    audioPlayer.volume = slider.value;

    NSLog(@"volume : %f",volume.value);
   
    NSLog(@"Playing");

}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
    // This code block is fired when we stop recording the audio....
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
    // your actions here
   
}


-(IBAction) stopPlaying{
    NSLog(@"stop playing");
    [audioPlayer stop];
    NSLog(@"Stopped");
}



That's it. Now run your code and record your own interesting videos.
this is all for the day. See you next time with more interesting things. Good luck! ;)

No comments:

Post a Comment