My app basically plays notes after each other and I want to show which note is being played at each time. Each note is a square in the UI and I have a 1-pixel view that moves from left to right to the note that is being played.
The problem is that I’m not sure how to do these two things at the same time. I can’t send a message from my sample-rendering function because that could be to slow and could cause glitches in my audio playback. Does anyone have any suggestions how I should update my UI to reflect what is being played?
My music playing code is based on this example and I think that the RenderTone method is run in a different thread. I want to move my 1-pixel view 1 pixel every time 1000 samples have been played (just an example, could also be more pr less) but I don’t know how to message the UI and send it updates on how many samples have been played.
So while a variation of the code below is being run I have to somehow update my UI.
OSStatus RenderTone(
void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData)
{
// Fixed amplitude is good enough for our purposes
const double amplitude = 0.25;
// Get the tone parameters out of the view controller
ToneGeneratorViewController *viewController =
(ToneGeneratorViewController *)inRefCon;
double theta = viewController->theta;
double theta_increment =
2.0 * M_PI * viewController->frequency / viewController->sampleRate;
// This is a mono tone generator so we only need the first buffer
const int channel = 0;
Float32 *buffer = (Float32 *)ioData->mBuffers[channel].mData;
// Generate the samples
for (UInt32 frame = 0; frame < inNumberFrames; frame++)
{
buffer[frame] = sin(theta) * amplitude;
theta += theta_increment;
if (theta > 2.0 * M_PI)
{
theta -= 2.0 * M_PI;
}
}
// Store the updated theta back in the view controller
viewController->theta = theta;
return noErr;
}
I would suggest that as various times in this code you use a simple block back to the main thread:
You can send those infrequently. You can run your RenderTone code in the highPriority queue so the mainQueue is only run when you have no essential work to do.