I am trying to figure out how to get moving average from a certain value I receive from my microphone. I have a frequencyChangedWithValue function calling my measuring method. This means that I get a changing value of frequency up to 10 times in a second. I am interested now how to make an average number from all of these changing values. How do I do it?
- (void)frequencyChangedWithValue:(float)newFrequency{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
self.currentFrequency = newFrequency;
[self performSelectorInBackground:@selector(filterFrequencyToGetBeats) withObject:nil];
[pool drain];
pool = nil;
}
- (void) filterFrequencyToGetBeats {
if (self.currentFrequency > 1000 && pointInTime % 2 == 0)
{
tm_start = mach_absolute_time();
pointInTime = pointInTime + 1;
}
else
if (self.currentFrequency > 1000 && pointInTime % 2 == 1)
{
pointInTime = pointInTime + 1;
tm_end = mach_absolute_time();
tm_elapsed = tm_end - tm_start;
mach_timebase_info(&info);
tm_nanoSeconds = tm_elapsed * info.numer / info.denom;
tm_milliSeconds = tm_nanoSeconds / (1000000);
tm_seconds = (tm_milliSeconds/1000);
fflush(stdout);
printf ( "| allocateAudio: %5lld milliseconds, (%12lld nano seconds)\n", tm_milliSeconds, tm_nanoSeconds );
}
}
I have one of these:
// MovingAverage.h
@interface MovingAverage : NSObject
@property (readonly, nonatomic) float movingAverage;
@property (readonly, nonatomic) float cumulativeAverage;
- (id)initWithPeriod:(NSUInteger)period;
- (void)addDatum:(NSNumber *)datum;
@end
// MovingAverage.m
#import "MovingAverage.h"
@interface MovingAverage ()
@property (strong, nonatomic) NSMutableArray *queue;
@property (assign, nonatomic) NSUInteger period;
@property (assign, nonatomic) NSUInteger count;
@property (assign, nonatomic) float movingAverage;
@property (assign, nonatomic) float cumulativeAverage;
@end
@implementation MovingAverage
- (id)initWithPeriod:(NSUInteger)period {
self = [self init];
if (self) {
_period = period;
// with arc
_queue = [NSMutableArray array];
// without arc
_queue = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addDatum:(NSNumber *)datum {
[self.queue insertObject:datum atIndex:0];
float removed = 0;
float datumf = [datum floatValue];
if (self.queue.count > self.period) {
removed = [[self.queue lastObject] floatValue];
[self.queue removeLastObject];
}
self.movingAverage = self.movingAverage - (removed / self.period) + (datumf / self.period);
// compute the cumulative average
self.cumulativeAverage = self.cumulativeAverage + (datumf - self.cumulativeAverage) / ++self.count;
}
// if non-ARC
- (void)dealloc {
[_queue release];
[super dealloc];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With