These lines of code do the same thing but sounds different?


#1

Hello I’m new here and I just coded my first sinewave generator and I came across this weird situation.

	for (auto sample = 0; sample < bufferToFill.numSamples; ++sample) {
		double x = MathConstants<double>::twoPi*frequency.getValue() / currentSampleRate;
                //CODE v1:
		buffer[sample] = std::sin(currentIteration*x)*(volume.getValue() / 100);
		currentIteration += 1;
                //CODE v2:
		buffer[sample] = std::sin(currentAngle)*(volume.getValue() / 100);
		currentAngle += x;
	}

The above is in my getNextAudioBlock() function. v1 and v2 both do the same thing, except v1 multiplies by x in the buffer[sample] statement while v2 multiplies by x in the currentAngle variable.
For some reason although they do the same thing, v1 generates a buzz everytime the frequency slider is moved while v2 doesn’t. Could anyone explain to me why that happens? And/or those lines of code are not actually equivalent?


#2

I’m trying to read this, but it looks like some of your code got messed up by the forum software stealing characters to use as formatting operators (which is why some of it is italicized). Could you wrap your code in ‘’’ <newline> <code> <newline> ‘’’ so it gets formatted correctly?


#3

Your currentIteration Variable will cause a phase jump when you change the frequency. You can verify this by taking pen and paper and calculate the values for an easy example.
Or simply imagine your iteration is one million and you change the frequency by 1Hz. Your phase will jump by 1 Million divided by fs. This will create a discontinuity, however in eps/(2 pi) of all cases it will fit :wink:

The second one will just increase the phase according to the new frequency, so you don’t get any glitches/discontinuities in your phase.


#4

Ohhh that explains it, Thanks!