Consistent oscillator periods

While I fixed the sawtooth oscillator problem, there was still something not quite right with the sound - and I noticed it in other oscillators, too. I was trying to figure out why that was.

I came to the conclusion that it was because the signal value was not properly coming back as zero at the start of each new period. This was causing a subtle tinny sound with the oscillators - not really noticeable in the sine wave, but it was noticeable in the other three. In the case of the square wave, we actually never want a value of zero, but I'll get to that.

The solution to this was to keep the position value within a small bound. So for a frequency of 428 and a sample rate of 44.1 khz, we can expect one period every 103 samples. The fix is to do the math to find out where in the period we are, and do the math to make sure our x value is no larger than 103.

This is done through simple modulo division. All I needed to do was calculate the period length in number of samples - an integer - and then do the mod operation on the provided position value. The code ended up looking like this.

You see that this is handled in my new getXValue function in Oscillator.kt. This makes the inheriting oscillator classes slightly more simple, since there's no need to calculate the x value within getSignal.

The square wave oscillator also has a pulse width feature. This allows us to adjust the ratio of the length of the top pulse to the bottom pulse. By default it's 0.5 - this means the top and bottom pulses will be equal. By shortening the pulse width, you shorten the top pulse and lengthen the bottom pulse. This results in a different sound and a differently-shaped wave:


I think the sound may still be slightly off, particularly for the triangle wave. That said, it's a lot better than it was before. I think next I will work on making the oscillators play a simple tune.

Comments