Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active November 3, 2021 01:30
Show Gist options
  • Save todbot/b8c7193627b3db82a603ce0af07db4bd to your computer and use it in GitHub Desktop.
Save todbot/b8c7193627b3db82a603ce0af07db4bd to your computer and use it in GitHub Desktop.
Try to make array waves that don't suck
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
@todbot
Copy link
Author

todbot commented Nov 3, 2021

Demo:

import waves

sin = waves.sine_wave(sample_frequency=2000, pitch=100)
squ = waves.square_wave(sample_frequency=2000, pitch=100)
saw = waves.sawtooth_wave(sample_frequency=2000, pitch=100)
tri = waves.triangle_wave(sample_frequency=2000, pitch=100)

print("--- sine");
for i in range(len(sin)):
    print("i:%d %d" % (i,sin[i]))

print("--- square")
for i in range(len(squ)):
    print("i:%d %d" % (i,squ[i]))

print("--- sawtooth")
for i in range(len(saw)):
    print("i:%d %d" % (i,saw[i]))

print("--- triangle")
for i in range(len(tri)):
    print("i:%d %d" % (i,tri[i]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment