Skip to content

Instantly share code, notes, and snippets.

@akaszynski
Created February 21, 2021 16:39
Show Gist options
  • Save akaszynski/085aefa1f6ee9e9eb911ab0559037f0e to your computer and use it in GitHub Desktop.
Save akaszynski/085aefa1f6ee9e9eb911ab0559037f0e to your computer and use it in GitHub Desktop.
Simple script to capture
"""
Simple script to turn the keyboard into a basic piano.
Install dependancies with:
$ pip install pynput pysinewave
$ sudo apt install libportaudio2
This script has the bonus "feature" to listen the entire keyboard input, so
when it's running, when typing outside of the terminal it will still play
sounds.
"""
DIRECTIONS = """
Simple piano. Press and/or hold keys on the home row to make a tone.
Middle C at H.
Supports sharp keys. For example, Press "shift c" to play C#
Press q to quit
"""
print(DIRECTIONS)
import time
from pynput.keyboard import Key, Listener
from pysinewave import SineWave
char_to_pitch = {
'a': -5,
'A': -4.5,
's': -4,
'S': -3.5,
'd': -3,
'D': -2.5,
'f': -2,
'F': -1.5,
'g': -1,
'G': -0.5,
'h': 0,
'H': 0.5,
'j': 1,
'J': 1.5,
'k': 2,
'K': 2.5,
'l': 3,
'L': 3.5,
';': 4,
':': 4.5,
"'": 5,
'"': 5.5,
}
sinewave = SineWave(pitch_per_second=1000000)
def on_press(key):
if hasattr(key, 'char'):
char = key.char
if char in char_to_pitch:
pitch = char_to_pitch[char]
sinewave.set_pitch(pitch)
sinewave.play()
def on_release(key):
if hasattr(key, 'char'):
char = key.char
sinewave.stop()
if char == 'q':
print('quitting')
return False
# Collect events until released
with Listener(on_press=on_press, on_release=on_release, supress=True) as listener:
listener.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment