Last active
November 3, 2021 01:30
-
-
Save todbot/b8c7193627b3db82a603ce0af07db4bd to your computer and use it in GitHub Desktop.
Try to make array waves that don't suck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import array | |
def sine_wave(sample_frequency: float, pitch: float): | |
"""Generate a single sine wav cycle at the given sampling frequency and pitch.""" | |
length = int(sample_frequency / pitch) | |
b = array.array("H", [0] * length) | |
for i in range(length): | |
b[i] = int(math.sin(math.pi * 2 * i / length) * ((2 ** 15) - 1) + 2 ** 15) | |
return b | |
def square_wave(sample_frequency: float, pitch: float): | |
"""Generate a single square wav cycle at the given sampling frequency and pitch.""" | |
sample_length = int(sample_frequency / pitch) | |
square = array.array("H", [0] * sample_length) | |
for i in range(sample_length // 2): | |
square[i] = 0xFFFF | |
return square | |
def sawtooth_wave(sample_frequency: float, pitch: float): | |
"""Generate a single sawtooth wav cycle at the given sampling frequency and pitch.""" | |
sample_length = int(sample_frequency / pitch) | |
saw = array.array("H", [0] * sample_length) | |
for i in range(sample_length): | |
saw[i] = int((i/sample_length) * 0xFFFF) | |
return saw | |
def triangle_wave(sample_frequency: float, pitch: float): | |
"""Generate a single triangle wav cycle at the given sampling frequency and pitch.""" | |
sample_length = int(sample_frequency / pitch) | |
half_length = sample_length//2 | |
tri = array.array("H", [0] * sample_length) | |
for i in range(half_length): | |
tri[i] = int(((i*2)/sample_length) * 0xFFFF) # wave goes up | |
tri[i+half_length] = int(((sample_length-(i*2))/sample_length) * 0xFFFF) # wave goes down | |
return tri | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: