Skip to content

Instantly share code, notes, and snippets.

@andfanilo
Created August 6, 2021 17:43
Show Gist options
  • Save andfanilo/117ad8217c6389f2862ebbd1053f714f to your computer and use it in GitHub Desktop.
Save andfanilo/117ad8217c6389f2862ebbd1053f714f to your computer and use it in GitHub Desktop.
Send and Receive MIDI data from device using MIDO
import time
import mido
import streamlit as st
EMPTY_DEVICE_PLACEHOLDER = "-"
LIGHT_PLACEHOLDER = "Light!"
NOTE_PLACEHOLDER = "Wait for note"
def main():
# For an unknown reason sometimes not all MIDI ports are immediately detected?
with st.sidebar:
if "initialized" not in st.session_state:
with st.sidebar:
with st.spinner("Wait for Ports to load..."):
time.sleep(3)
st.session_state["initialized"] = True
selected_action = st.selectbox(
"What do you want to do?", (LIGHT_PLACEHOLDER, NOTE_PLACEHOLDER)
)
selected_midi_device = st.selectbox(
"Select MIDI to send to"
if selected_action == LIGHT_PLACEHOLDER
else "Select MIDI to receive from",
[EMPTY_DEVICE_PLACEHOLDER]
+ (
mido.get_output_names()
if selected_action == LIGHT_PLACEHOLDER
else mido.get_input_names()
),
)
if selected_midi_device is not EMPTY_DEVICE_PLACEHOLDER:
if selected_action == LIGHT_PLACEHOLDER:
with mido.open_output(selected_midi_device) as outport:
outport.send(mido.Message("note_on", channel=0, note=55))
time.sleep(5)
outport.send(mido.Message("note_off", channel=0, note=55))
if selected_action == NOTE_PLACEHOLDER:
with mido.open_input(selected_midi_device) as inport:
st.markdown("Waiting for note input")
msg = inport.receive()
st.write(f"Received MIDI message: {msg}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment