Here's a barebones application that will play the generated frequency on demand. You did not indicate whether to do iOS or OSX, so I went for OSX, as it is a bit easier (not to bother with audio categories). If you need iOS, you can find out the missing bits by learning the basics of the audio session and sharing the default audio device for the RemoteIO audio device.
Please note that this intention is to demonstrate the basic basics of the Core Audio / Audio Unit. You probably want to look into the AUGraph API if you want to start getting more complicated than that (also in the interest of providing a clean example, I don't do any error checking. Always do error checking when working with Core Audio).
To use this code, you need to add the AudioToolbox and AudioUnit to your project.
You can call AudioOutputUnitStart() and AudioOutputUnitStop() at will to start / stop sound playback. If you want to dynamically change the frequency, you can pass a pointer to a struct containing both double and another representing the frequency you need.
Be careful of the render callback. It is called from a real-time thread (not from the same thread as your main loop loop). Failsafe callbacks obey some fairly stringent time requirements, which means that there are many things in your callback that you should not do, for example:
- Allocate memory
- Waiting for a mutex
- Reading from a file on disk
- Objective-C messaging (yes, seriously.)
Please note that this is not the only way to do this. I just demonstrated it this way, since you marked this core audio. If you donβt need to change the frequency, you can simply use AVAudioPlayer with a pre-created sound file containing a sine wave.
There is also Novocaine , which hides a lot of this verbosity from you. You can also look in the Audio Queue API, which works pretty much like the Core Audio sample I wrote, but it separates you a bit from the hardware (i.e., it is less strict about how you behave in the rendering callback).
admsyn
source share