Getting sound in decibel - ios

I want the sound which i am recording from my iPhone mic in decibels. I am using
[recorder peakPowerForChannel:]
but it giving in -160 to 0 range and i have requirement of taking 140 dBs as
a threshold. Can anyone help me with the same…?
Here is the Below sample code which i am trying :
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
[recordSettings setObject:[NSNumber numberWithInt:kAudioFormatAppleLossless] forKey: AVFormatIDKey];
[recordSettings setObject:[NSNumber numberWithFloat:22050.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: AVAudioQualityLow] forKey: AVEncoderAudioQualityKey];
NSError* error = nil;
recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:recordSettings error:&error];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
NSTimer *blowTimer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(timerTask) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer: blowTimer
forMode: NSDefaultRunLoopMode];
-(void)timerTask
{
[recorder updateMeters];
float averagePower = [recorder averagePowerForChannel:0];
}

Related

AVAudioRecorder in iOS 9 Not working

I'm using AVAudioRecorder to record a audio file. The code I'm using works perfectly fine in iOS 8 and below but since the latest update of iOS 9 the recording seems to have stopped working.
I tried logging the properties of AVAudioRecorder object and even after calling the "record" function in AVAudioRecorder the isRecording is showing as NO and when the "stop" function is called i get the call back in the delegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag; with success flag as NO
audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(#"audioSession: %# %ld %#", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVEncoderBitRateKey];
[recordSetting setValue :[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
[recordSetting setValue :[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
recorderFilePath = [NSString stringWithFormat:#"%#/%#.m4a", DOCUMENTS_FOLDER,#"sample"];
NSLog(#"RecorderFilePath : %#",recorderFilePath);
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputAvailable;
[recorder record];
Please advise if i'm doing something wrong in the code.
Try this:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey, [NSNumber numberWithFloat:44100.0], AVSampleRateKey, [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,nil];
// [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
// Initiate and prepare the recorder
if (recorderHelium)
{
recorderHelium = nil;
}
recorderHelium = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:recordedAudioFilePath] settings:recordSetting error:nil];
recorderHelium.delegate = self;
recorderHelium.meteringEnabled = YES;
[recorderHelium prepareToRecord];
[recorderHelium record];
And also import and include these files:
#import <AudioToolbox/AudioServices.h>
#include <AudioToolbox/AudioToolbox.h>

is it possible recording through the 3.5mm headphone jack in iphone sdk

I am making an app and i have created a functionality to record voice with iPhone but recording is not possible with 3.5mm headphone jack, its only working with iPhone mic. So please Suggest me what should i do.
My Recording code is:
-(void)recording
{
[recordBtn setImage:[UIImage imageNamed:#"green_btn.png"] forState:UIControlStateNormal];
NSLog(#"startRecording");
inc_Bar=0.0;
// [self performSelector:#selector(stopRecording) withObject:nil afterDelay:10.0f];
[self increaseProgressBar];
progressBarTimer = [NSTimer scheduledTimerWithTimeInterval:recordingLength/1000.0f target:self selector:#selector(increaseProgressBar) userInfo:nil repeats:YES];
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:sampleRateFloat] 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:sampleRateFloat] 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 *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/recordTest.caf", recDir]];
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");
}
Thanks. Please Help.
Based on documentation:
If a headset is plugged in at the time you set this property’s value tokAudioSessionOverrideAudioRoute_Speaker, the system changes the audio routing for input as well as for output: input comes from the built-in microphone; output goes to the built-in speaker.

After record sound file, this can't heard in iPad Air only

I have an app in the Apple Store with voice recording capability. I migrate to Xcode 5.0.2 and SDK 7.
I have no problem with this feature in devices with iOS 6 or 7 except with iPad Air.
This is my record Sound routine:
+(void) startRecording:(NSString *)fileName :(NSString *)fileType
{ NSError* theError = nil;
BOOL result = YES;
// Init audio with record capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
result = [audioSession setCategory:AVAudioSessionCategoryRecord error:&theError];
if (!result)
{
NSLog(#"setCategory failed %#", theError);
}
result = [audioSession setActive:YES error:nil];
if (!result)
{
NSLog(#"setActive failed %#", theError);
}
// Verify if you have granted to use microphone. iOS 7 or later
if ([audioSession respondsToSelector:#selector(requestRecordPermission:)]) {
[audioSession requestRecordPermission:^(BOOL granted) {
if (granted) {
// Record Sound
[self recordNow:fileName :fileType];
}
else {
// Microphone disabled code
NSLog(#"Microphone is disabled..");
// We're in a background thread here, so jump to main thread to do UI work.
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:#"Microphone Access Denied"
message:#"This app requires access to your device's Microphone.\n\nPlease enable Microphone access for this app in Settings / Privacy / Microphone"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil] show];
});
}
}];
}
else { // iOS 6
// Record sound
[self recordNow:fileName :fileType];
}
}
// Record Sound
+(void) recordNow:(NSString *)fileName :(NSString *)fileType {
recordEncoding = ENC_AAC;
// Microphone enabled code
if (kDebugMode) {
NSLog(#"Microphone is enabled..");
}
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:16] forKey:AVEncoderBitRateKey];
[recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#.%#", recDir, fileName, fileType]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
[audioRecorder recordForDuration:[[NSUserDefaults standardUserDefaults] integerForKey:kRecordForDuration]];
}
After a lot research inside this site, i found an excellent comment that saves my day here:
"Now that I've removed the AVEncoderBitRateKey and value, it also works on the 5S."
So, i just comment this row and fix it !!
[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVEncoderBitRateKey];
I can hear again the record sound in iPad Air !
Why happen this? I did not know yet, but its works and maybe you have the same problem and just want to leave a log about this case in this website.

iOS7 strange issue. Recorder not stopped

i am developing one app in that app i have used the AudioRecorder. my recorder doesent stop when app is close. red status bar shows when my app is background.
used this code...
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
//[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[session setCategory:AVAudioSessionCategoryRecord 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
delegate.recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
delegate.recorder.delegate=self;
delegate.recorder.meteringEnabled = YES;
[delegate.recorder prepareToRecord];
//[recorder record]; // Do not start recording here
[delegate.recorder updateMeters];
level = [delegate.recorder peakPowerForChannel:0];
//AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//[audioSession setActive:NO error:nil];
timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self
selector:#selector(updateAudioMeter)
userInfo:nil
repeats:YES];
-(void)updateAudioMeter
{
AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
[delegate.recorder updateMeters];
level = [delegate.recorder averagePowerForChannel:0];
NSLog(#"%f",level);
if(level<=-120)
{
[delegate.recorder record];
}
else
{
[delegate.recorder stop];
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[recorder stop];
}
but when my app is close the red status bar shows means my iPhone5 not stop the recording. where may i wrong please help me solve this.

Recorder delegate method not called

NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *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];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
//Start the actual Recording
[recorder record];
[recorder updateMeters];
level = [recorder peakPowerForChannel:0];
NSLog(#"%f",level);
i have used this code in viewDidload() method to record a sound sound get in level.
i want to call the deleget method when device get the sound.
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
NSLog(#"Level is %f",level);
}
this method not called.
i am setting recorder delegate in .h file but not called this method why this is happening.
help me to do this.
Thanks in advance.
Are you actually storing the AVAudioRecorder instance somewhere? If you are not then it is likely deallocated by the time the above code finishes.
Try this
-(void)initialiceAudio{
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
AVAudioSession *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:5000.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;
[player setVolume: 1.0];
[recorder prepareToRecord];
}
-(IBAction)record:(id)sender {
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
recordBtn.selected=YES;
tabBtn.selected = YES;
tabBtn.userInteractionEnabled = NO;
// Start recording
[recorder record];
} else {
}
}
-(void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
recorder = nil;
player = nil;
spinnerView = nil;
UploadAudioViewController *upload = [[UploadAudioViewController alloc]initWithNibName:#"UploadAudioViewController" bundle:nil];
NSLog(#"recorder url----%#",recorderurl);
upload.audioURL = recorderurl;
[self.navigationController pushViewController:upload animated:YES];
}
and make sure - you used AVAudioRecorderDelegate and AVAudioPlayerDelegate

Resources