follow a repeating pattern Frequency Number of cycles per second e.g. 444.0Hz Repeat 440 cycles per second Square wave (waveform) https://en.wikipedia.org/wiki/Square_wave_(waveform)
changes continuously within a cycle Digital A continuous signal amplitude cannot be recorded Instead, record so that it appears continuous a fixed number of samples This number is "sample rate" Sample rate The number of samples per second
second Time per sample: 1 second / sample rate Increment in current phase per sample: frequency / sample rate class SquareOscillator def tick(frequency:) @phase += frequency.to_f / sample_rate @phase -= 1.0 if @phase >= 1.0 # Phase is managed from 0 to 1, reset when reaching 1 @phase end
def generate(frequency:) # Get the current phase within the cycle phase = tick(frequency: frequency) # 1 if in the first half, -1 if in the second half phase < 0.5 ? 1.0 : -1.0 end end Collecting samples produces a square wave