top | item 30254085

(no title)

prutschman | 4 years ago

> this is quite frankly very surprising to me.

If we let t be time in seconds, and f be frequency in Hz, the sine wave formula is y = sin(2pitf). The 2pi is the periodicity of the sine function. If f is 1, we sweep through 2pi once per second. If we let f be 2, then it sweeps through two times per second, and so on.

So, you can think of the lookup index as being the tf part, but with t counting in integer fractions of a second, with the caveat that you'll want to perform some interpolation between values.

If the waveform were more complex than a sine wave, then in the general case this "skipping agead" could cause distortion. A sine wave is one of a couple special cases (square wave being another, and arguably it's "cheating") where you're not skipping "too far" to cause distortion. (That relates to the Nyquist sampling theorem and low-pass filtering, as kens mentions)

discuss

order

nyanpasu64|4 years ago

A high-pitched square wave absolutely will have aliasing when played without interpolation. In Audacity, try creating a 30 second square chirp from 6000 to 16000 Hz, and listen to the weird and wacky frequencies far away from the intended frequency.

anyfoo|4 years ago

Because a square wave is actually infinitely many sine waves (at odd harmonic frequencies) added together. So, almost all of these will lie outside the Nyquist frequency, which is half the sampling rate for real sampling.

In practice, only the first few odd harmonics are strong enough to really matter, but with a high-pitched square wave you still need oversampling and lowpass filtering to get rid of those in the general case without aliasing[1].

However, if you choose the frequency of your square wave right (to make the sample rate an integer multiple), the aliasing products will just be reflected back to be exactly on top of the "actual" harmonics, neatly sounding like a perfect square wave again (in theory). Matching well with our intuition of what happens with the actual signal, if you do the "skipping" for such a square wave.

[1] Or maybe not if your goal is really only generating square waves: Just don’t generate these harmonics. Your 16kHz square wave without aliasing will just sound like a sine wave anyway, because your ear cannot hear its harmonics.