Skip to content

Instantly share code, notes, and snippets.

@bartolsthoorn
Created April 23, 2012 19:41
Show Gist options
  • Save bartolsthoorn/2473329 to your computer and use it in GitHub Desktop.
Save bartolsthoorn/2473329 to your computer and use it in GitHub Desktop.
Multiple signal generator!
// MULTIPLE SIGNAL GENERATOR!
__block float *phases = nil;
[audioManager setOutputBlock:^(float *data, UInt32 numFrames, UInt32 numChannels)
{
float samplingRate = audioManager.samplingRate;
NSUInteger activeSignalCount = [tones count];
// Initialize phases
if (phases == nil) {
NSLog(@"Initializing float array");
phases = new float[10];
for(int z = 0; z <= 10; z++) {
phases[z] = 0.0;
}
}
NSEnumerator * enumerator = [tones objectEnumerator];
id frequency;
UInt32 c = 0;
while(frequency = [enumerator nextObject])
{
for (int i=0; i < numFrames; ++i)
{
for (int iChannel = 0; iChannel < numChannels; ++iChannel)
{
float theta = phases[c] * M_PI * 2;
if (c == 0) {
data[i*numChannels + iChannel] = sin(theta);
} else {
data[i*numChannels + iChannel] = data[i*numChannels + iChannel] + sin(theta);
}
}
phases[c] += 1.0 / (samplingRate / [frequency floatValue]);
if (phases[c] > 1.0) phases[c] = -1;
}
c++;
}
// Normalize data with active signal count
float signalMulti = 1.0 / (float(activeSignalCount) * (sqrt(2.0)));
vDSP_vsmul(data, 1, &signalMulti, data, 1, numFrames*numChannels);
// Apply master volume
float volume = masterVolumeSlider.value;
vDSP_vsmul(data, 1, &volume, data, 1, numFrames*numChannels);
// Measure dB
float maxAmp = abs(data[0]);
for (int i=0; i < numFrames; ++i)
{
for (int iChannel = 0; iChannel < numChannels; ++iChannel)
{
if (abs(data[i*numChannels + iChannel]) > maxAmp) {
maxAmp = abs(data[i*numChannels + iChannel]);
}
}
}
printf("Maximum Amp in dB: %f\n", 20 * log10f(maxAmp));
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment