How to Record Audio on Iphone With Avaudiorecorder

How do I record audio on iPhone with AVAudioRecorder?

Actually, there are no examples at all.
Here is my working code. Recording is triggered by the user pressing a button on the navBar.
The recording uses cd quality (44100 samples), stereo (2 channels) linear pcm. Beware: if you want to use a different format, especially an encoded one, make sure you fully understand how to set the AVAudioRecorder settings (read carefully the audio types documentation), otherwise you will never be able to initialize it correctly. One more thing. In the code, I am not showing how to handle metering data, but you can figure it out easily.
Finally, note that the AVAudioRecorder method deleteRecording as of this writing crashes your application. This is why I am removing the recorded file through the File Manager. When recording is done, I save the recorded audio as NSData in the currently edited object using KVC.

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

- (void) startRecording{

UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered target:self action:@selector(stopRecording)];
self.navigationItem.rightBarButtonItem = stopButton;
[stopButton release];

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[audioSession setActive:YES error:&err];
err = nil;
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);

recordSetting = [[NSMutableDictionary alloc] init];

[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];

NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: [err localizedDescription]
delegate: nil
[alert show];
[alert release];

//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;

BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: @"Audio input hardware not available"
delegate: nil
[cantRecordAlert show];
[cantRecordAlert release];

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


- (void) stopRecording{

[recorder stop];

NSURL *url = [NSURL fileURLWithPath: recorderFilePath];
NSError *err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey];

//[recorder deleteRecording];

NSFileManager *fm = [NSFileManager defaultManager];

err = nil;
[fm removeItemAtPath:[url path] error:&err];
NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]);

UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered target:self action:@selector(startRecording)];
self.navigationItem.rightBarButtonItem = startButton;
[startButton release];


- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag

NSLog (@"audioRecorderDidFinishRecording:successfully:");
// your actions here


Record the sound through AVAudioRecorder

Once go through below code it might be helpful to you.
First take object for AVAudioRecorder as AVAudioRecorder *audioRecorder;


NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//here i took cache directory as saved directory you can also take NSDocumentDirectory
docsDir = [dirPaths objectAtIndex:0];

NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];//at this path your recorded audio will be saved

NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:

[NSNumber numberWithInt:AVAudioQualityMin],

[NSNumber numberWithInt:16],

[NSNumber numberWithInt: 2],

[NSNumber numberWithFloat:44100.0],

NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]initWithURL:soundFileURL settings:recordSettings error:&error];

if( !audioRecorder ) {

UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: [error localizedDescription] delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];


if ( error )
NSLog( @"error: %@", [error localizedDescription] );
else {
[audioRecorder prepareToRecord];
[self recordAudio];//Mehod to Record Audio


Now define method to record Audio,

 -(void) recordAudio
if (!audioRecorder.recording)
audioRecorder.delegate = self;
[audioRecorder recordForDuration:10];//Here i took record duration as 10 secs



Now you can write AvAudio record DelegateMethods as,

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:      (BOOL)flag
//Your code after sucessful recording;
-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
NSLog(@"Encode Error occurred");

hope it will helps to you...

Using AVAudioRecorder to record voice

AVAudioRecorder does not need anymore the error parameter:

init(URL url: NSURL, settings settings: [String : AnyObject]) throws

Also, I needed to unwrap the filePath, as suggested in a previous answer:

func recordSound(){
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

let recordingName = "my_audio.wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0]

let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
} catch _ {

audioRecorder.delegate = self
audioRecorder.meteringEnabled = true

How to record audio as mp3 file by using AvAudiorecorder in iOS


[NSNumber numberWithInt:kAudioFormatMPEGLayer3] forKey:AVFormatIDKey

However it's impossible to encode mp3 format at IPhone because of royalty.

Can AVAudioRecorder be used to record audio coming from your iOS app?

As far as I can tell, there's no way to do this with AVAudioRecorder. You must use Audio Units.

Record audio iOS

Is there a way to record device audio on the iPhone?

Record samples being played with OpenAL

Offline audio recording on iOS with OpenAL

Related Topics

Leave a reply