ios , get float level mic updateMesters when mic is recording audio - avaudioplayer

here is my code for recording now how can get the level sound input in mic by sample UIlable float number
i think i will use this function but how can i use this in rec.h & rec.m file
(void)updateMeters
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
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];
recordedTmpName = [[NSString alloc] initWithFormat:#"%.0f.%#", [NSDate timeIntervalSinceReferenceDate] * 1000.0, #"aac"];
temporaryRecFile= [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:recordedTmpName]];
recorder = [[ AVAudioRecorder alloc] initWithURL:temporaryRecFile settings:recordSetting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];

During recording, you have to call updateMeters periodically, and get the average power by
- (float)averagePowerForChannel:(NSUInteger)channelNumber
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
- (void) handleTimer
{
[recorder updateMeters];
label.text = [NSString stringWithFormat:#"lf",[recorder averagePowerForChannel:0]];
}
To see more information, you can visit AVAudioRecorder Class Reference

Related

Repeating Audio in WatchKit (AVAudioPlayer?)?

I am wanting to loop a local audio file in my Apple Watch App. Currently I am using AVAudioPlayerNode and AVAudioEngine which works well but I cannot figure out how to loop the sound.
I noticed that I can use AVAudioPlayer, which has the handy "numberOfLoops" but, for some reason AVAudioPlayer is not working on the watch. I have no idea why.
Here is my current code to play a sound:
_audioPlayer = [[AVAudioPlayerNode alloc] init];
_audioEngine = [[AVAudioEngine alloc] init];
[_audioEngine attachNode:_audioPlayer];
AVAudioFormat *stereoFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
[_audioEngine connect:_audioPlayer to:_audioEngine.mainMixerNode format:stereoFormat];
if (!_audioEngine.isRunning) {
NSError* error;
[_audioEngine startAndReturnError:&error];
}
NSError *error;
NSBundle* appBundle = [NSBundle mainBundle];
NSURL *url = [NSURL fileURLWithPath:[appBundle pathForResource:#"FILE_NAME" ofType:#"mp3"]];
AVAudioFile *asset = [[AVAudioFile alloc] initForReading:url error:&error];
[_audioPlayer scheduleFile:asset atTime:nil completionHandler:nil];
[_audioPlayer play];
Here is the code i've tried to use for AVAudioPlayer, but does not work:
NSError *audioError;
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"FILE_NAME" ofType:#"mp3"]] error:&audioError];
player.numberOfLoops = MAXFLOAT;
player.delegate = self;
[player play];
I am using WatchKit 5.0(+).
You can loop your AVAudioFile by recursively scheduling it:
__block __weak void (^weakSheduleFile)(void);
void (^scheduleFile)(void);
weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };
scheduleFile();
I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:
scheduleFile();
scheduleFile();
If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):
AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];
__block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];
if (![asset readIntoBuffer:srcBuffer error:&error]) {
NSLog(#"Read error: %#", error);
abort();
}
AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];
AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
if (srcBuffer) {
AVAudioBuffer *result = srcBuffer;
srcBuffer = NULL;
*outStatus = AVAudioConverterInputStatus_HaveData;
return result;
} else {
*outStatus = AVAudioConverterInputStatus_EndOfStream;
return NULL;
}
}];
assert(status != AVAudioConverterOutputStatus_Error);
[_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
[_audioPlayer play];

Playing 2 sounds with AVAudioPlayer without sleep();

I have this 2 sounds playing in a scrollview using AVAudioPlayer.
The problem is that the sleep() is creating lags and I need an alternative to playing two sounds one after the other more easily without the sleep function.
PS: the name of the file is given by the page in the scrollView in which the user is.
if( nextPage!=6 ) {
[scrMain scrollRectToVisible:CGRectMake(0, nextPage*250, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
pgCtr.currentPage=nextPage;
NSString *path;
NSError *error;
path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"pas%02i",nextPage+1] ofType:#"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
player.volume = 0.5f;
[player prepareToPlay];
[player setNumberOfLoops:0];
[player play];
}
sleep(1);
NSString *path2;
NSError *error2;
path2 = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"passun%02i",nextPage+1] ofType:#"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path2])
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:&error2];
player.volume = 0.5f;
[player prepareToPlay];
[player setNumberOfLoops:0];
[player play];
}
How can I do this?

plist - NSMutableDictionary - 0x0

I have a problem:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
NSString *settingPath = [[[NSString alloc] init] autorelease];
settingPath = [[NSBundle bundleWithPath:filePath] pathForResource:#"Root" ofType:#"plist"];
NSMutableDictionary *plist = [[[NSMutableDictionary alloc] init] autorelease];
plist = [NSMutableDictionary dictionaryWithContentsOfFile:settingPath];
after this plist is nil, adress ist 0x0 ... but why ?
Can anyone help me ?
Below is some code that should work OK:
NSString* path = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"plist"];
NSDictionary* dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
Note that the plist must be valid, otherwise you will get a null value.
Also, note that you don't need to use alloc/init to create a variable if you're just going to overwrite its value in another call.

NSException error seems to occur randomly

This code was working fine, now for some reason I'm getting an NSException error that's generating a SIGABRT at the following line of code...
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:wbPopOverController] autorelease];
Here's the method it's located in...
-(IBAction)showPop:(id)sender {
//close any open popovers
[self.popoverController dismissPopoverAnimated:NO];
// Initialize wbPopUpViewController
PopoverAircraftClass *wbPopOverController = [[PopoverAircraftClass alloc] initWithNibName:#"PopoverAircraftClass" bundle:[NSBundle mainBundle]];
wbPopOverController.contentSizeForViewInPopover = CGSizeMake(175, 216);
wbPopOverController.delegate = self; //for update
[wbPopOverController setAircraftList:aircraftList withCurrentValue:activeRegistration];
// Object converted to UIPopOverController (retained so we can reference it)
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:wbPopOverController] autorelease];
self.popoverController.passthroughViews = [NSArray arrayWithObject: self.view];
[self.popoverController presentPopoverFromRect:[sender frame] inView:self.layoutViewIB permittedArrowDirections:UIPopoverArrowDirectionUp animated:NO];
[wbPopOverController release];
}
I'm new at this as you can probably tell. Any ideas as to what's generating the NSException?

Loading database at start up slows down the app

i m not sure how to describe this as i m new with all the developing and i m really looking forward to an answer from you guys. I know you can be very busy but please try to HELP me!
Here it goes. I have an app that loads a very large database (although it only has 100 entries it contains HiRes images (100MB) ).
At start up a tableview presents the rows -records (using only 3 attributes from the database). However it seems that the WHOLE database (including the images) is loaded at start up!
IS THERE A WAY TO ONLY LOAD THE 3 attributes (something like "select") when the app starts and then when the user moves to didselectrowatindexpath load the rest of the record?
Because i have NO IDEA where to look or what to do i would appreciate some coding help!
here is the code i m using:
#pragma mark -
#pragma mark App support
- (NSFetchedResultsController *)resetFetchedResultsController:(NSPredicate *)predicate cached:(BOOL)cached
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Records" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *partDescriptor = [[NSSortDescriptor alloc] initWithKey:#"displayOrder" ascending:YES];
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: partDescriptor, nameDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
if (predicate != nil)
[fetchRequest setPredicate:predicate];
NSString *cacheName = nil;
if (cached)
cacheName = #"Root";
NSFetchedResultsController *aFetchedResultsController = [[[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:cacheName] autorelease];
aFetchedResultsController.delegate = self;
[fetchRequest release];
[partDescriptor release];
[nameDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
return aFetchedResultsController;
}
- (void)showRecords:(Records *)records animated:(BOOL)animated {
.
RecordsDetailViewController *detailViewController = [[RecordsDetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
detailViewController.records = records;
[self.navigationController pushViewController:detailViewController animated:animated];
[detailViewController release];
}
#pragma mark -
#pragma mark Table view methods
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor lightGrayColor];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger count = [[fetchedResultsController sections] count];
if (count == 0) {
count = 1;
}
return count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger numberOfRows = 0;
if ([[fetchedResultsController sections] count] > 0) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
numberOfRows = [sectionInfo numberOfObjects];
}
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *RecordCellIdentifier = #"RecordCellIdentifier";
RecordTableViewCell *recordCell = (RecordTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RecordCellIdentifier];
if (recordCell == nil) {
recordCell = [[[RecordTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:RecordCellIdentifier] autorelease];
recordCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
[self configureCell:recordCell atIndexPath:indexPath];
return recordCell;
}
- (void)configureCell:(RecordTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// Configure the cell
Records *records = (Records *)[fetchedResultsController objectAtIndexPath:indexPath];
cell.records = records;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.searchDisplayController.isActive)
[self.tableView reloadData];
Records *records = (Records *)[fetchedResultsController objectAtIndexPath:indexPath];
[self showRecords:records animated:YES];
}
//this is from the RecordTableViewCell.m to show you the attributes i m using:
#pragma mark -
#pragma mark Record set accessor
- (void)setRecord:(Record *)newRecord {
if (newRecord != record) {
[record release];
record = [newRecord retain];
}
imageView.image = [UIImage imageNamed:#"icon.png"];
nameLabel.text = record.name;
overviewLabel.text = record.overview;
partLabel.text = record.part;
}
thanks again...
I would separate the large file from the metadata, because I like to have the freedom to manage these expensive resources seParately. Then I could store them differently, eg filesystem, or http server. This allows me to cache them or send them to remote locAtions proactively to reduce the download times
The rest of the table can then fit in less blocks in the database so less disk access is needed. Many databases do this internally anyway, eg postgresql
You can the just refer to the heavy resource by Id
Ok here it goes. I ve gave up the idea of loading separately the attributes that i need at start up.
What i ve done AND NOW WORKS FLAWLESSLY is to do create RELATIONSHIPS in my model. Images are now loading only when called!
This solution was in my mind but because i had already populated my database it was difficult for me to repeat this step.
However i m glad that i did!
NOW it works as it should!!
Happy Developer!!

Resources