Sinewave Generator Produces Horrible Buzz

Hello I’m a newbie here and I can’t seem to even create a proper sinewave generator.
Could someone please point out what’s wrong with my code? It sort of works but always produces a horrible buzzing sound. The sliders and variables are all setup properly. So I’m thinking it has something to do with my getNextAudioBlock function:

void MainComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
    for (int channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel){
		auto* buffer = bufferToFill.buffer->getWritePointer(channel,bufferToFill.startSample);
		for (auto sample = 0; sample < bufferToFill.numSamples; ++sample) {
			buffer[sample] = std::sin(  sample * MathConstants<double>::twoPi * frequencySlider.getValue() / currentSampleRate  ) * (  volumeSlider.getValue() / 100  );

You need to use a modulo counter in the sine calculation, not the sample index of the current buffer.

The phase of your sinewave starts over again with each call of getNextAudioBlock(...) as it starts with zero (auto sample = 0) -> your sine starts from 0, this causes your buzzing.

To avoid that, you need a member variable like phase, which you increment for each sample by the right amount. This tutorial will help you:

BTW: When you write ``` before and after your code, it will be formatted nicely.

1 Like

Thank you! It worked!