ios,objective-c,iphone,audio , How can I get my iPhone to listen for sound frequencies above a certain threshold?

## Question:

Tag: ios,objective-c,iphone,audio

I'm interested in getting my iOS app to turn on the microphone and only listen for frequencies above 17000 hz. If it hears something in that range, I'd like the app to call a method.

I was able to find a repository that detects frequency: https://github.com/krafter/DetectingAudioFrequency

And here is a post breaking down FFT:
Get Hz frequency from audio stream on iPhone

Using these examples, I've been able to get the phone to react to the strongest frequency it hears, but I'm more interested in just reacting to the above 17000 hz frequencies.

The fact that I wrote that code helps me answering this question but the answer probably only applies to this code.

You can easily limit the frequencies you listen to just by trimming that output array to a piece that contains only the range you need.

In details: To be simple - array[0..255] contains your audio in frequency domain. For example you sample rate was 44100 when you did FFT. Then maximum frequency you can encode is 22050. (Nyquist theorem).

That is array[0] contains value for 22050/256=86.13 Hz. Array[1] contains value for 86.13*2 = 172.26 Hz, array[2] contains value for 86.13*3 = 258.39 Hz. And so on. Your full range is distributed across those 256 values. (and yes, precision suffers)

So if you only need to listen to some range, let's say above 17000Hz, you just take a piece of that array and ignore the rest. In this case you take 17000/86.13=197 to 255 subarray and you have it. Only 17000-22050 range.

In my repo you modify strongestFrequencyHZ function like that:

``````static Float32 strongestFrequencyHZ(Float32 *buffer, FFTHelperRef *fftHelper, UInt32 frameSize, Float32 *freqValue) {
Float32 *fftData = computeFFT(fftHelper, buffer, frameSize);
fftData[0] = 0.0;
unsigned long length = frameSize/2.0;
Float32 max = 0;
unsigned long maxIndex = 0;

Float32 freqLimit = 17000; //HZ

Float32 freqsPerIndex = NyquistMaxFreq/length;
unsigned long lowestLimitIndex = (unsigned long) freqLimit/freqsPerIndex;

unsigned long newLen = length-lowestLimitIndex;
Float32 *newData = fftData+lowestLimitIndex; //address arithmetic
max = vectorMaxValueACC32_index(newData, newLen, 1, &maxIndex);
if (freqValue!=NULL) { *freqValue = max; }
Float32 HZ = frequencyHerzValue(lowestLimitIndex+maxIndex, length, NyquistMaxFreq);
return HZ;
``````

}

I did some address arithmetic in there so it looks kind of complicated. You can just take that fftData array and do the regular stuff.

Other things to keep in mind:

Finding strongest freq. is easy. You just find maximum in that array. That's it. But in you case you need to monitor the range and find when it went from regular weak noise to some strong signal. In other words when stuff peaks, and this is not so trivial, but possible. You can probably just set some limit above which the signal becomes detected, although this not the best option.

I would rather be optimistic about this cause in real life you can't see much noise at 18000Hz around you. The only thing a can remember of are some old TVs that produce that high pitched sound when they're on.

# Related:

## App crashes when i start typing in uiseachbar in uitableview

ios
I am making a project in which i am fetching addressbook in my tableview with the help of NSObject class. Now , I allocated a UISearchbar in it , but when i start typing , the app crashes with the following error :---- 'Can't use in/contains operator with collection (not...

## iOS 8 Swift CS193P Calculator Bug Switch Operation

ios,swift
I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

## Extra table cells when UITableViewController is embedded into a Container in a UIViewController

ios,swift,uitableview,uiviewcontroller
In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

## UITapGestureRecognizer sender is the gesture, not the ui object

ios,xcode,swift,uigesturerecognizer
I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

## Unexpectedly found nil while unwrapping an Optional value - Plist

ios,swift,plist
i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

## Getting video from Asset Catalog using On Demand ressources

ios,xcode,xcode7,ios9,asset-catalog
I attributed to my .mp4 video the "tokyo" tag for example, and set it as installed during the app installation. Now before I was using a Path to get it from my resources, now it's different because it's located on the Asset Catalog. After found documentations, I tried something like...

## animating a view on top of uitableview

ios,swift,autolayout
I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

## How can I fix crash when tap to select row after scrolling the tableview?

ios,xcode,swift,uitableview,tableviewcell
I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

## iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

ios,objective-c,swift
I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

## MFMessageComposeViewControllerDelegate not being called

ios,swift
I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

## Adding Image And title both to UIsegmentControl IOS

ios,uiimage,title,uisegmentedcontrol
Is there a way so that you can set both image and title of UISegmentControl simultaneously, so that image appear next to the title , just like image appear next to title in UIButton. I am trying but if I set image of Selected segment of UISegmentControl then title disappears...

## try to recover views from custom cell

ios,uitableview
I made a custom cell from my storyboard, with an UIImageView and a UILabel. Each of them have a tag 100 for the imageView and 102 for UILabel. I try to get them in my datasource method but as below, they are still nil and I don't know why. ...

## SpriteKit collision angle of line and circle is odd

ios,sprite-kit,skphysicsbody
Suppose a circle is enclosed in a diamond, and the circle heads due right. I would expect a series of continual 90 degree angles as the circle draws a square within the diamond. What I'm seeing, however, is that the circle eventually gets pushed toward the center of the diamond...

## Override UITabBarController Icon Selection

ios,objective-c,uitabbarcontroller
I'm using a standard UITabBarController with icons at the bottom, each bringing to it's ownViewController. My question is basically: Is there a way to override what happens when an icon is selected rather then directly bringing them to the view? Reason being is because I'm adding a login screen to...

## After an insert into the UITableView : custom the cell

ios,objective-c,uitableview
I'm using insertion into my UITableView with this : Skill * newSkill = [[Skill alloc] init]; newSkill.name = @"Nouvelle compétence"; newSkill.pathPicto = @"generic"; [self.skills insertObject:newSkill atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; It works great but now I want that the inserted cell be...

## Transferring an Xcode project to another computer with all files/frameworks

ios,xcode,frameworks,transfer,projects
I am trying to copy over my Xcode project from one computer to another but it seems to lose frameworks and the locations for the images although i copied those too. PS I am using xcode and coding an app with a friend. Is there a useful source that can...

## How can I show ONLY the date (and not the time) using NSDateFormatter?

ios,iphone,swift
I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

## How to draw each a vertex of a mesh as a circle

How to draw each a vertex of a mesh as a circle?

## Is it possible to obtain an unique iCloud user ID on cocoa?

My iOS app is currently on beta in TestFlight, and as a way to retribute to the nice people who helped me test it I would like to offer them some goodies such as, for instance, the full final version of the app for free. For this, I was thinking...

## UITabBarViewController doesn't rotate - iOS

I have a UITabBarViewController that contains 5 tabs and a login view which is not part of my tab bar, in my settings I have set that I support all device orientations. but when I run my app, only my login view is the only which rotates. I have created...

## Set color CFAttributedStringRef

ios,objective-c
I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate . in my...

## Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring
What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

## Implementing Applovin Ads with Swift & SpriteKit

ios,swift,applovin
I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

## Scaling everything up and down for different devices in UIStoryboard

ios,uistoryboard
Is it possible to have the storyboard scale everything up or down depending on the screen size or do I have to do it programmatically? For example the UI on iPhone 6 plus would look exactly like the one on iPhone 5 but just larger.

## Build error after I localized Info.plist

ios,objective-c,xcode,swift,localization
I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

## NS_ENUM as property in protocol

ios,objective-c,automatic-ref-counting
I came across to strange behaviour. I used to have: @property (nonatomic) ApplicationState applicationState; directly in my Application class. Now it's extracted to protocol @protocol ApplicationProtocol <NSObject> @property (nonatomic) ApplicationState applicationState; ApplicationState is Enum typedef NS_ENUM(NSUInteger, ApplicationState) { ApplicationStateNormal = 0, ApplicationStateExpanded = 1, ApplicationStateMaximized = 2 }; Now. It...

## How to get time difference based on GMT on Swift

ios,swift
I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

## How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

ios,swift,ios8,uiimagepickercontroller,ios8.3
- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

## Characters and Strings in Swift

ios,string,swift,unicode,character
Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

## ios8 Timezone parsing changed?

ios,nsdateformatter
Has the parsing for timzones changed in iOS8? I try to parse the date "2014-09-03 12:20:38.000 +0200" with this code and get nil: -(NSDateFormatter*) dateAndTimeFormatter{ if(!_dateAndTimeFormatter){ _dateAndTimeFormatter = [[NSDateFormatter alloc]init]; [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"]; _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle; _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle; } return _dateAndTimeFormatter; } alternatively [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd...

## Cursor doesn't update in NSTextField as it autoresizes when resizing the enclosing NSWindow

objective-c,cocoa,nstextfield,autoresize,nscursor
I have an NSTextField that autoresizes. Its text is centered. When I start typing in the field and then resize the enclosing NSWindow, the cursor stays where it's at rather than repositioning to the appropriate place : I've also made an XCode project demonstrating this problem : https://www.dropbox.com/sh/cohhmslyl9ti43b/AAC6ULteopsQCMDsEArJU15Ta?dl=0 Does anyone...

## Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

## Call method after asynchronous request obj-c

ios,objective-c,asynchronous,uiviewcontroller,nsobject
In my app I init a new object, where there is method which calls NSURLConnection's sendAsynchronousRequest method. After the request, I would like to call a method in the caller UIViewController. I tried to use a static method but I then I can't control IBOutlets. How can I do this?...

## What is the best practice add video background view?

ios,objective-c,swift,video
I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

## It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

ios,objective-c,swift,uitextfield,uilabel
In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

## NSString to NSDate doesn't work

ios,objective-c,nsdateformatter
now it works with this code: NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSDate *date = [dateFormatter dateFromString:myDate]; [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; NSString *dateString = [dateFormatter stringFromDate:date]; cell.timeLabel.text = dateString; ...

## Do I have to use both of these methods?

ios,swift,uitableview
When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

## How to create UITableViewCells with complex content in order to keep scrolling fluent

ios,swift,uitableview,cocoa-touch,ios-charts
I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

## IOS - Adjust cell height based on content

ios,uitableview,autolayout
im trying to build apps that have tableview cell similiar with twitter, there are text and images. My problem is i want to insert the image above the text. While it can be text only. So if there are no image, the text will be in position (0,0). And if...