-
-
Save wulab/84b2f9f4d35c07be9895a7789a64a027 to your computer and use it in GitHub Desktop.
Simple 1 octave piano in Python with live input
This file contains hidden or 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 numpy as np | |
import simpleaudio as sa | |
import os, sys, termios, time, tty | |
# Key mapping: | |
# W E T I U | |
# A S D F G H J K | |
# | |
# Which translates to: | |
# C#D# F#G#A# | |
# C D E F G A B C | |
# | |
# Press = or + to increase tone duration, | |
# - or _ to decrease, x or X to exit. | |
seconds = .2 | |
def _synth(f): | |
frequency = int(f) | |
t = np.linspace(0, seconds, seconds * 44100, False) | |
note = np.sin(frequency * t * 2 * np.pi) | |
audio = note * (2**15 - 1) / np.max(np.abs(note)) | |
audio = audio.astype(np.int16) | |
play_obj = sa.play_buffer(audio, 1, 2, 44100) | |
play_obj.wait_done() | |
def _getInput(): | |
fd = sys.stdin.fileno() | |
old_settings = termios.tcgetattr(fd) | |
try: | |
tty.setraw(fd) | |
ch = sys.stdin.read(1) | |
finally: | |
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) | |
print(ch) | |
return ch | |
while True: | |
try: | |
pressed = _getInput() | |
if pressed in ("=" or "+"): # Increase tone duration | |
seconds += .1 | |
print(seconds) | |
elif pressed in ("-" or "_"): # Decrease tone duration | |
seconds -= .1 | |
if seconds <= 0: # Don't allow the time to go to 0 | |
seconds = .1 | |
print(seconds) | |
elif pressed in ("x" or "X"): # Press X to exit | |
sys.exit() | |
elif pressed == "a": _synth(261.63) # C | |
elif pressed == "w": _synth(277.18) # C# | |
elif pressed == "s": _synth(293.66) # D | |
elif pressed == "e": _synth(311.13) # D# | |
elif pressed == "d": _synth(329.63) # E | |
elif pressed == "f": _synth(349.23) # F | |
elif pressed == "t": _synth(369.99) # F# | |
elif pressed == "g": _synth(392) # G | |
elif pressed == "y": _synth(415.3) # G# | |
elif pressed == "h": _synth(440) # A | |
elif pressed == "u": _synth(466.16) # A# | |
elif pressed == "j": _synth(493.88) # B | |
elif pressed == "k": _synth(523.25) # C | |
else: | |
pass | |
except: | |
if pressed in ("x", "X"): print("Exiting..."); sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment