Created
March 14, 2018 19:47
-
-
Save dapetcu21/ada7323536ab2ff9e8c7b51318be3c0f to your computer and use it in GitHub Desktop.
Raspberry Piano synth
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
#!/usr/bin/env python | |
import RPi.GPIO as GPIO | |
import time | |
import subprocess | |
from os import path | |
from os import listdir | |
import sys | |
import threading | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
sound_fonts_dir = path.join(path.dirname(path.realpath(sys.argv[0])), 'fonts') | |
sound_fonts = [f for f in listdir(sound_fonts_dir) if path.isfile(path.join(sound_fonts_dir, f))] | |
sound_font_index = sound_fonts.index("Full Grand Piano.sf2") | |
fsynth_process = None | |
def is_running(): | |
global fsynth_process | |
return fsynth_process != None and fsynth_process.poll() == None | |
def kill_process(): | |
global fsynth_process | |
if not is_running(): | |
fsynth_process = None | |
return | |
fsynth_process.kill() | |
fsynth_process.wait() | |
fsynth_process = None | |
def connect_thread_func(): | |
time.sleep(.200) | |
for i in range(20): | |
if subprocess.call(['aconnect', '24:0', '128:0']) == 0: | |
break | |
time.sleep(.500) | |
def start_process(): | |
global fsynth_process, sound_fonts, sound_font_index | |
if is_running(): | |
kill_process() | |
sound_font = path.join(sound_fonts_dir, sound_fonts[sound_font_index]) | |
print('Using sound font: ' + sound_font) | |
fsynth_process = subprocess.Popen(['fluidsynth', '-a', 'alsa', '-is', sound_font]) | |
t = threading.Thread(target=connect_thread_func) | |
t.start() | |
def on_toggle(channel): | |
if is_running(): | |
kill_process() | |
else: | |
start_process() | |
def on_next(channel): | |
global sound_font_index, sound_fonts | |
if is_running(): | |
sound_font_index = (sound_font_index + 1) % len(sound_fonts) | |
start_process() | |
def on_prev(channel): | |
global sound_font_index, sound_fonts | |
if is_running(): | |
sound_font_index = (sound_font_index - 1) % len(sound_fonts) | |
start_process() | |
GPIO.add_event_detect(25, GPIO.RISING, callback=on_toggle, bouncetime=100) | |
GPIO.add_event_detect(24, GPIO.RISING, callback=on_next, bouncetime=100) | |
GPIO.add_event_detect(23, GPIO.RISING, callback=on_prev, bouncetime=100) | |
while True: | |
time.sleep(10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment