Record sound when speaking to mic - objective-c

I want to write controller which handles sound recording. It should record sound when there is sound in mic.
I have working code on recording sound when button is pressed.
-(IBAction) startRecording
{
NSLog(#"startRecording");
audioRecorder = nil;
// Init audio with record capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
// if(recordEncoding == ENC_PCM)
//{
[recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
[recordSettings setObject:[NSNumber numberWithFloat:500.0] forKey: AVSampleRateKey];//44100.0
[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];
// NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];
NSURL *url = [NSURL URLWithString:[self copyFile:#"recordTest.caf"]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
[audioRecorder setDelegate:self];
if ([audioRecorder prepareToRecord] == YES){
[audioRecorder record];
NSLog(#"recording");
}else {
int errorCode = CFSwapInt32HostToBig ([error code]);
NSLog(#"Error: %# [%4.4s])" , [error localizedDescription], (char*)&errorCode);
}
}
So is it possible to record or monitor sounds from mic input and start recording when sound is above for example 1000 Hz ?
I would also appreciate for literature on this.
Thanks.

hope it wil help you Download the link l

Related

AVAudioRecorder prepareToRecord always return NO

Here's the code I am using to trigger recording. Can someone suggest solution?
[AVAudioRecorder prepareToRecord] always return NO
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
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
{
NSNumber *formatObject;
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];
}
[recordSettings setObject:formatObject 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];
}
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
BOOL canRecord = [audioRecorder prepareToRecord];
if ([audioRecorder prepareToRecord] == YES){
[audioRecorder record];
}else {
int errorCode = CFSwapInt32HostToBig ([error code]);
NSLog(#"Error: %# [%4.4s])" , [error localizedDescription], (char*)&errorCode);
}
You need to activate the AVAudioSession:
[audioSession setActive:YES error:&error];

can't able to save recorded audio iOS?

I Want to save the recorded audio in local documents directory
After that i want to play the Saved audio file
Audiofile is not created in documents directory?
I've tried with the following code What I am doing wrong??
NSString *temp1=[NSString stringWithFormat:#"%#.m4a",temp];
NSLog(#"=====>>%#",temp1);
NSArray *pathComponents=[NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)lastObject],temp1, nil];
NSURL *outputFileURL=[NSURL fileURLWithPathComponents:pathComponents];
if (isRecording==NO) {
isRecording=YES;
NSLog(#"recording started");
session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
[session setActive:YES error:nil];
// Start recording
[recorder record];
}
else
{
NSLog(#"recording stopped");
[recorder stop];
NSData *audioData=[NSData dataWithContentsOfURL:outputFileURL];
[audioData writeToURL:outputFileURL atomically:YES];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil];
[player prepareToPlay];
[player play];
[player setVolume:1.0];
isRecording=NO;
}
Try this code
-(IBAction)btnS1AudioPressed:(id)sender
{
audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
NSMutableDictionary *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];
NSString *AudioName=[NSString stringWithFormat:#"TestAudio.caf"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
audioPath = [documentsDirectory stringByAppendingPathComponent:AudioName];
NSURL *url = [NSURL fileURLWithPath:audioPath];
err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(audioData)
{
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[url path] error:&err];
}
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder)
{
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];
return;
}
[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
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[cantRecordAlert show];
return;
}
[recorder recordForDuration:(NSTimeInterval) 10000];
}
- (IBAction) stopRecording:(id)sender
{
[recorder stop];
}
I've found the mistake I made
NSArray *pathComponents=[NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)lastObject],temp1, nil];
In the above code I used NSDocumentationDirectory instead of NSDocumentsDirectory

Sending record audio POST

I record audio with AVAudioRecorder:
audioRecorder = nil;
//Initialize audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
//Override record to mix with other app audio, background audio not silenced on record
OSStatus propertySetError = 0;
UInt32 allowMixing = true;
propertySetError = AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixing), &allowMixing);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
NSLog(#"Mixing: %lx", propertySetError); // This should be 0 or there was an issue somewhere
[[AVAudioSession sharedInstance] setActive:YES error:nil];
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] initWithCapacity:0];
if (recordEncoding == ENC_PCM) {
[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];
} else {
NSNumber *formatObject;
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;
}
[recordSetting setValue:formatObject forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
[recordSetting setValue:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/recordTest.caf", recDir]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&error];
if (!audioRecorder) {
NSLog(#"audioRecorder: %# %d %#", [error domain], [error code], [[error userInfo] description]);
return;
}
// audioRecorder.meteringEnabled = YES;
//
BOOL audioHWAvailable = audioSession.inputAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: #"Warning"
message: #"Audio input hardware not available"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[cantRecordAlert show];
return;
}
if ([audioRecorder prepareToRecord]) {
[audioRecorder record];
NSLog(#"recording");
} else {
// int errorCode = CFSwapInt32HostToBig ([error code]);
// NSLog(#"Error: %# [%4.4s])" , [error localizedDescription], (char*)&errorCode);
NSLog(#"recorder: %# %d %#", [error domain], [error code], [[error userInfo] description]);
}
And I want to send it in POST header. How can i do it correctly? I'm guessing that i should have NSData and then convert it into NSString. Am i right? If true how can I convert AVAudioRecorder output to NSData?
Here is a sample application I done for understanding the audio file uploading.
You can use the following method to send the recorded audio using POST:
- (IBAction) pushLoader
{
NSURL *pathURL = urlOfAudioFile; //File Url of the recorded audio
NSData *voiceData = [[NSData alloc]initWithContentsOfURL:pathURL];
NSString *urlString = #"http://iroboticshowoff.com/img2/upload.php"; // You can give your url here for uploading
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init]autorelease];
#try
{
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".caf\"\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:voiceData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
UIAlertView *alert = nil;
if(error)
{
alert = [[UIAlertView alloc]initWithTitle:#"Message" message:#"Error in Uploading the File" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
else
{
NSLog(#"Success %#",returnString);
alert = [[UIAlertView alloc]initWithTitle:#"Message" message:#"File get uploaded" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
[alert show];
[alert release];
alert = nil;
[returnString release];
returnString = nil;
boundary = nil;
contentType = nil;
body = nil;
}
#catch (NSException * exception)
{
NSLog(#"pushLoader in ViewController :Caught %# : %#",[exception name],[exception reason]);
}
#finally
{
[voiceData release];
voiceData = nil;
pathURL = nil;
urlString = nil;
}
}

Objective C: OpenAL changing Pitch issue

im having a hard time on OpenAL framework... i just want to change the pitch in playback action... what code is missing in my project.. im new in objective c,iOS development. hoping for your kind consideration, thanks in advance.. here is my code for the three button (RECORD,STOP,Play)..
-(void)startRecording:(UIButton *)sender
{ //for recording
recStopBtn.hidden = NO;
recStopBtn.enabled =YES;
playRecBtn.enabled = NO;
loading.hidden = NO;
[loading startAnimating];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
recordSetting = [[NSMutableDictionary alloc] init];
// We can use kAudioFormatAppleIMA4 (4:1 compression) or kAudioFormatLinearPCM for nocompression
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
// We can use 44100, 32000, 24000, 16000 or 12000 depending on sound quality
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
// We can use 2(if using additional h/w) or 1 (iPhone only has one microphone)
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
// These settings are used if we are using kAudioFormatLinearPCM format
//[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
//[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.caf", DOCUMENTS_FOLDER];
NSLog(#"recorderFilePath: %#",recorderFilePath);
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(audioData)
{
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[url path] error:&err];
}
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder){
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];
return;
}
//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
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[cantRecordAlert show];
return;
}
// start recording
[recorder record];
lblStatusMsg.text = #"Recording...";
//recIcon.image = [UIImage imageNamed:#"rec_icon.png"];
//progressView.progress = 0.0;
//timer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
}
-(void)stopRecord:(UIButton *)sender
{
loading.hidden = YES;
[loading stopAnimating];
recStartBtn.enabled = YES;
recStartBtn.hidden = NO;
playRecBtn.hidden = NO;
playRecBtn.enabled = YES;
recStopBtn.enabled = NO;
recStopBtn.hidden = YES;
[recorder stop];
[timer invalidate];
lblStatusMsg.text = #"Stopped";
// recIcon.image = [UIImage imageNamed:#"rec_icon2.png"];
}
-(void)playRecord:(UIButton *)sender
{
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.caf", DOCUMENTS_FOLDER];
NSURL *urlRecord = [NSURL fileURLWithPath:recorderFilePath isDirectory:NO];
NSError *errorRecord;
soundRecord = [[AVAudioPlayer alloc] initWithContentsOfURL:urlRecord error:&errorRecord];
[soundRecord play];
}
-(void)changePitch:(UIButton *)sender
{
alSourcef(recorderFilePath, AL_PITCH, 1.2f);//this kinda troubles me,the source. =(
[soundRecord play];//this one also...
}
The first argument of the alSourcef method isn't an NSString file path, it's an ALuint representing an audio source.
See the example oalTouch (specifically the oalPlayback class) for how to set up an OpenAL source from a URL.

How to save audio file after recording in iPhone?

Hi I have code which dose recording, but I can not figure it out how to save and when I come back again then I can play same recorded file again?
I am using below code for recording -
-----
-(IBAction) startRecording
{
NSLog(#"startRecording");
[audioRecorder release];
audioRecorder = nil;
// Init audio with record capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
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 {
NSNumber *formatObject;
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];
}
[recordSettings setObject:formatObject 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];
}
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
if ([audioRecorder prepareToRecord] == YES){
[audioRecorder record];
} else {
int errorCode = CFSwapInt32HostToBig ([error code]);
NSLog(#"Error: %# [%4.4s])" , [error localizedDescription], (char*)&errorCode);
}
NSLog(#"recording");
}
----
please let me know that how can i save this audio file? so i can re-open app again and play that recorded file.
Thanks
Append a valid path to the name of the file you are going to save with. For example get a writable path of your application's document directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recordDir = [paths objectAtIndex:0];
Append this recordDir to the file name:
NSString *recordFile = [recordDir stringByAppendingPathComponent: #"recordTest.caf"];
Use this full path to get a url for:
NSURL *url = [NSURL fileURLWithPath:recordFile];
Now use this url to create a AVAudioRecorder.
cleaned viewLoad in ViewController.m :
- (void)viewDidLoad
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
[recorder setDelegate:self];
[super viewDidLoad];
}
edited record in ViewController.m :
- (IBAction) record
{
NSError *error;
// Recording settings
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
[settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
[settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
[settings setValue: [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];
NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath_ = [searchPaths objectAtIndex: 0];
NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];
//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 prepareToRecord];
[recorder record];
}
edited playback in ViewController.m:
-(IBAction)playBack
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
temporaryRecFile = [prefs URLForKey:#"Test1"];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
player.delegate = self;
[player setNumberOfLoops:0];
player.volume = 1;
[player prepareToPlay];
[player play];
}
and added a new dateString method to ViewController.m:
- (NSString *) dateString
{
// return a formatted string for a file name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"ddMMMYY_hhmmssa";
return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:#".aif"];
}
Now it can load the last recorded file via NSUserdefaults loading it with:
//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
temporaryRecFile = [prefs URLForKey:#"Test1"];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
in (IBAction)playBack. temporaryRecFile is a NSURL variable in my ViewController class.
declared as following ViewController.h :
#interface SoundRecViewController : UIViewController <AVAudioSessionDelegate,AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
......
......
NSURL *temporaryRecFile;
AVAudioRecorder *recorder;
AVAudioPlayer *player;
}
......
......
#end
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSArray *documentsFolders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[documentsFolders objectAtIndex:0] stringByAppendingPathComponent:#"Recording.aiff"];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:path] completionBlock:^(NSURL *assetURL, NSError *error){
/*notify of completion*/
NSLog(#"AssetURL: %#",assetURL);
NSLog(#"Error: %#",error);
if (!error) {
//video saved
[[self appDelegate] showAlertWithTitle:#"Audio Saved" message:#""];
}
else{
[[self appDelegate] showAlertWithTitle:#"Error" message:error.domain];
}
}];