Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active August 29, 2020 14:06
Show Gist options
  • Save theoknock/bb21c815dcf3c0c0e643a1d0644a09a3 to your computer and use it in GitHub Desktop.
Save theoknock/bb21c815dcf3c0c0e643a1d0644a09a3 to your computer and use it in GitHub Desktop.
Initializes a two-channel (stereo) PCM audio buffer for computed audio data (versus pre-recorded audio)
AVAudioPCMBuffer * (^bufferSamples)(AVAudioFrameCount, AVAudioChannelCount, AVAudioFormat *, double) = ^AVAudioPCMBuffer *(AVAudioFrameCount frame_count, AVAudioChannelCount channel_count, AVAudioFormat *audioFormat, double duration_n_secs)
{
AVAudioFrameCount frameCount = audioFormat.sampleRate * duration;
AVAudioPCMBuffer *pcmBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:audioFormat frameCapacity:frameCount];
pcmBuffer.frameLength = frameCount;
float *left_channel = pcmBuffer.floatChannelData[0];
float *right_channel = (channelCount == 2) ? pcmBuffer.floatChannelData[1] : nil;
int amplitude_frequency = arc4random_uniform(8) + 4;
for (int index = 0; index < frame_count; index++)
{
double time = index / frame_count;
double frequency = sinf(2.0 * M_PI * (frequency * duration) * time) * 0.5; // Multiply the frequency by the duration to ensure the right pitch, regardless of the length of the buffer
if (left_channel) left_channel[index] = frequency;
if (right_channel) right_channel[index] = frequency;
}
return pcmBuffer;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment