How to record audio in objective c for iphone app in .amr format? - ios

I have used following code to record audio. It works perfectly for .caf format.
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];
But for .amr if i change extension to .amr as per below it is not working for me to record audio.
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:#"sound.amr"];
can any body guide me how to record and save audio in .amr format?

try below Code, might be useful to you..
AppDelegate *del = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//set path & name for Recording Audio
NSString *dataPath=[del.path_Folder_Document copy];
NSString *filePath = [NSString stringWithFormat:#"%#/Images_Audio/%#.3gp", dataPath,[ARR_Img_File_Name_Moment objectAtIndex:pos]];
NSLog(#"Audio File Path =%#",filePath);
NSURL *tmpFileUrl = [NSURL fileURLWithPath:filePath];
//set Record Setting
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
nil];
NSError *error = nil;
//Prepare Recorder to Start Recording Audio
recorder = [[AVAudioRecorder alloc] initWithURL:tmpFileUrl settings:recordSettings error:&error];
recorder.delegate = self;
[recorder prepareToRecord];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
[session setActive:YES error:nil];
//Start Recording Audio ..
if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
NSLog(#"Writable Pathforimage_Audio 1st>> %#", filePath);
}else
{
NSLog(#"Not Writable");
}
[recorder record];
NSLog(#"its recording audio...");

Related

How to set settings to get recorded audio file size in kb?

I'm working on audio recording and uploading. While uploading 10secs audio I'm getting the 4GB data, I browsed and followed one of the answers in StackOverflow, changed settings as shown below and audio file format to .3gp, but data size not reduced.
-(void) startRecording{
[_recordButton setTitle:#"Stop" forState:UIControlStateNormal];
NSError *error;
// Recording settings
NSLog(#"%f", [[AVAudioSession sharedInstance] sampleRate]);
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
[settings setValue: [NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[settings setValue: [NSNumber numberWithFloat:2000.0] forKey:AVSampleRateKey];
[settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[settings setValue: [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];
[settings setValue:[NSNumber numberWithFloat:12000.0] forKey:AVEncoderBitRateKey];
NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath_ = [searchPaths objectAtIndex: 0];
NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:#"AudioName.3gp"];
// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];
//Save recording path to preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setURL:url forKey:#"Test1"];
[prefs synchronize];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// Create recorder
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
recorder.delegate=self;
[recorder recordForDuration:10];
[self startTimerToMoveSlider];
}
Can anybody please guide me
Finally solved audio file size issue, here is my code for recording 30seconds audio and getting file size nearly 60kb-70kb.
-(void) startRecording{
[_recordButton setTitle:#"Stop" forState:UIControlStateNormal];
NSError *error;
NSString *pathToSave = [NSString stringWithFormat:#"%#/MySound.m4a", DOCUMENTS_FOLDER];
// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];
// Recording settings
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,[NSNumber numberWithInt:12000],AVEncoderBitRateKey,
nil];
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&error];
//Save recording path to preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setURL:url forKey:#"Test1"];
[prefs synchronize];
// Create recorder
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
recorder.delegate=self;
[recorder prepareToRecord];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[recorder recordForDuration:30];//recording for 30secs
[self startTimerToMoveSlider];//to move slider while recording
}
Note : #define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]

What is the recommended encoding for caf audio files using AVAudioRecorder

If I want to record to a "caf" audio file on iOS, what's the recommended audio encoding? I think kAudioFormatMPEGLayer2 is right but I can't seem to find a definitive answer using google. Here's my code if that's helpful.
NSString *audioFilePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:path];
_audioFileURL = [NSURL fileURLWithPath:audioFilePath];
_audioQuality = [NSNumber numberWithInt:AVAudioQualityHigh];
_audioEncoding = [NSNumber numberWithInt:kAudioFormatMPEGLayer2];
_audioChannels = [NSNumber numberWithInt:2];
_audioSampleRate = [NSNumber numberWithFloat:44100.0];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
_audioQuality, AVEncoderAudioQualityKey,
_audioEncoding, AVFormatIDKey,
_audioChannels, AVNumberOfChannelsKey,
_audioSampleRate, AVSampleRateKey,
nil];
NSError *error = nil;
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:_audioFileURL
settings:recordSettings
error:&error];
_audioRecorder.delegate = self;

What is the best microphone recording settings for AVAudio?

So I have the current code:
- (void)viewDidLoad
{
[super viewDidLoad];
//for recording audio
_stopButton.enabled = NO;
_playButton.hidden = true;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:#"recording.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithFloat:44100.0], AVSampleRateKey,
[NSNumber numberWithInt:1], AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityHigh], AVSampleRateConverterAudioQualityKey,
[NSNumber numberWithInt:128000], AVEncoderBitRateKey,
[NSNumber numberWithInt:16], AVEncoderBitDepthHintKey,
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];
}
//----------------------------
//end
}
And the player:
- (IBAction)playAudio:(id)sender {
[_playButton setEnabled:NO];
if (!_audioRecorder.recording)
{
_stopButton.enabled = YES;
_recordButton.enabled = NO;
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:_audioRecorder.url
error:&error];
_audioPlayer.volume = 5;
_audioPlayer.delegate = self;
if (error)
NSLog(#"Error: %#",
[error localizedDescription]);
else
[_audioPlayer play];
}else{
NSLog(#"errormax");
}
}
I have the _audioPlayer.volume at 5 because any lower you can barely here it. But it peeks and sounds extremely distorted at that volume. Why can it not sound like "Voice Memos" where it plays it back at a reasonable volume without it distorting?
What are the best quality settings for this?
I personaly prefer PCM encoding, I've had better quality using it.
try:
NSDictionary *recordSettings =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
[NSNumber numberWithFloat:44100.0], AVSampleRateKey,
[NSNumber numberWithInt:2], AVNumberOfChannelsKey,
[NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
nil];
or to make it more readable:
NSDictionary * recordSetting;
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];
Adjust your function like this:
- (IBAction)playAudio:(id)sender {
[_playButton setEnabled:NO];
if (!_audioRecorder.recording)
{
_stopButton.enabled = YES;
_recordButton.enabled = NO;
//force the session to play to come out of speakers!
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:_audioRecorder.url
error:&error];
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
if (error)
NSLog(#"Error: %#",
[error localizedDescription]);
else
[_audioPlayer play];
}else{
NSLog(#"errormax");
}
}
It's because of audio session category "AVAudioSessionCategoryPlayAndRecord". It always play audio in receiver unless you explicitly change the overrideOutputAudioPort. You may have to add listener for AVAudioSessionRouteChangeNotification to change the category based on your out put. Anyway why this headache, just use AVAudioSessionCategoryRecord before you start recording and AVAudioSessionCategoryPlayback before you start player.
//Player
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
NSError *setCategoryError = nil;
[audioSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
//Recorder
newRecorder = [[AVAudioRecorder alloc]initWithURL:fileURL settings:recordSettings error:&error];
NSError *setCategoryError = nil;
[audioSession setCategory: AVAudioSessionCategoryRecord error: &setCategoryError];

ios - Recording Audio After VIdeo play

I can't record audio after playing a video, if I record before playing the video no problem but then I have to close the application to record again.
I can't record audio after playing a video, if I record before playing the video no problem but then I have to close the application to record again.
Record Audio:
- (IBAction)recordAudio:(id)sender {
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];
}
if (!_audioRecorder.recording)
{
_playButton.enabled = NO;
_stopButton.enabled = YES;
[_audioRecorder record];
}
}
Do this before recording the Audio:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

iOS, no recording sound in my iPad, in the simulator works fine

Hi I have a very strange problem in the simulator works perfect but when I charge the app to the iPad it does not work. Any idea?
Here I create all the variables to make it work.
- (void)viewDidLoad {
[super viewDidLoad];
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];
}
}
I have some buttons for record, play and stop. So these are the codes for all of them.
-(void) recordAudio{
if (!audioRecorder.recording){
recordButton.enabled = NO;
playButton.enabled = NO;
saveButton.enabled = NO;
stopButton.enabled = YES;
[audioRecorder record];
}
}
-(void)stop{
recordButton.enabled = YES;
playButton.enabled = YES;
saveButton.enabled = YES;
stopButton.enabled = NO;
if (audioRecorder.recording){
[audioRecorder stop];
}
else if (audioPlayer.playing){
[audioPlayer stop];
}
}
-(void) playAudio{
if (!audioRecorder.recording){
recordButton.enabled = NO;
stopButton.enabled = YES;
saveButton.enabled = NO;
if (audioPlayer)
audioPlayer=nil;
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:audioRecorder.url
error:&error];
audioPlayer.delegate = self;
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
[audioPlayer play];
}
}
finally I found a solution. To my previous code I add this lines inside the ViewdidLoad.
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
[audioSession setActive:YES error: &error];
and for the settings I added this:
[NSNumber numberWithInt:kAudioFormatAppleIMA4], AVFormatIDKey
I copy the code from http://www.iphoneam.com/blog/index.php?title=using-the-iphone-to-record-audio-a-guide&more=1&c=1&tb=1&pb=1 and the idea of using AVAudioSession came from How to record and play sound in iPhone app?
If you need the complete code is this one.
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error = nil;
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
[audioSession setActive:YES error: &error];
playButton.enabled = NO;
stopButton.enabled = NO;
saveButton.enabled = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
docsDir = [HSAudioController pathToDocumentsFolder];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:#"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatAppleIMA4], AVFormatIDKey,
[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16], AVEncoderBitRateKey,
[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0], AVSampleRateKey,
nil];
audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL
settings:recordSettings
error:&error];
NSLog(#"%#",audioRecorder.url);
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[audioRecorder prepareToRecord];
}
}

Resources