import time
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import fluidsynth
fs = fluidsynth.Synth()
fs.start(driver="alsa")
sfid0 = fs.sfload("Audio - Sound Font - Sonic Implants Session Drums.sf2")
fs.program_select(0, sfid0, 0, 0)
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# channel state and settings
MIDI_NOTES = [48, 38, 51, 50, 55, 49, 50, 51];
NUMBER_OF_CHANNELS = 6
MILLIS_BETWEEN_PICKS_AND_OFF = 50
MILLIS_BETWEEN_TWO_OF_THE_SAME_NOTE = 10
channel_state = [0]*NUMBER_OF_CHANNELS
channel_pick = [0]*NUMBER_OF_CHANNELS
channel_pick_time = [0]*NUMBER_OF_CHANNELS
channel_thrushhold = [30, 30, 30, 20, 60, 30, 30, 30]
channel_state_millis = [0]*NUMBER_OF_CHANNELS
#millis = int(round(time.time() * 1000))
# Main program loop.
while True:
# Read all the ADC channel values in a list.
values = [0]*NUMBER_OF_CHANNELS
for i in range(NUMBER_OF_CHANNELS):
# The read_adc function will get the value of the specified channel (0-7).
values[i] = mcp.read_adc(i)
#Stat 0 - IDLE
if channel_state[i] == 0:
#if we cross the threshhold
if values[i] > channel_thrushhold[i] and channel_state_millis[i] + MILLIS_BETWEEN_TWO_OF_THE_SAME_NOTE <= int(round(time.time() * 1000)) :
#set state to 1
channel_state[i] = 1
channel_state_millis[i] = int(round(time.time() * 1000))
elif channel_state[i] == 1:
# while till we over the pick
if channel_pick[i] < values[i]:
#play note
fs.noteon(0, MIDI_NOTES[i] , 127)
#set state to 2
channel_state[i] = 2
channel_state_millis[i] = int(round(time.time() * 1000))
else:
# save last pick
channel_pick[i] = values[i]
elif channel_state[i] == 2:
#if the note is playing for long enough
if channel_state_millis[i] + MILLIS_BETWEEN_PICKS_AND_OFF <= int(round(time.time() * 1000)):
#note off
fs.noteoff(0, MIDI_NOTES[i])
#clear the pick
channel_pick[i] = 0
#set state back to IDLE
channel_state[i] = 0
channel_state_millis[i] = int(round(time.time() * 1000))
Comments