def __initialize(self, enableDJM): self.midiin, port_name = open_midiinput("Traktor Virtual Output") print("Midi device: %s" % port_name) if enableDJM: self.djm850_midiiin, port_name_djm = open_midiinput("USB MIDI") print("Midi device: %s" % port_name_djm) self.midiin.ignore_types(False, False, False)
def __init__(self,in_port,out_port): print("Initialize MIDI CONTROL") global input_dict self.input_port = in_port self.midiin, self.portname_in = open_midiinput(self.input_port) self.Handler = MidiInputHandler(self.portname_in) self.midiin.set_callback(self.Handler) self.output_port = out_port self.midiout, self.portname_out = open_midioutput(self.output_port) self.color = 0x01 self.cc0 = CONTROL_CHANGE | 0x00 self.cc1 = CONTROL_CHANGE | 0x01 self.cc2 = CONTROL_CHANGE | 0x02 self.cc3 = CONTROL_CHANGE | 0x03 self.cc4 = CONTROL_CHANGE | 0x04 self.cc5 = CONTROL_CHANGE | 0x05 self.cc6 = CONTROL_CHANGE | 0x06 self.cc8 = CONTROL_CHANGE | 0x08 self.makeRingBlink(0x00) self.makeRingBlink(0x04) self.makeRingBlink(0x08) self.makeRingBlink(0x0B) self.makeRainbow(0x01) self.makeLedBlink(0x05) self.stopBlink(0x0B)
def main(args=None): clock = MIDIClockReceiver(float(args[0]) if args else None) try: m_in, port_name = open_midiinput(args[0] if args else None) except (EOFError, KeyboardInterrupt): return 1 m_in.set_callback(clock) # Important: enable reception of MIDI Clock messages (status 0xF8) m_in.ignore_types(timing=False) try: print("Waiting for clock sync...") while True: time.sleep(1) if clock.running: if clock.sync: print("%.2f bpm" % clock.bpm) else: print("%.2f bpm (no sync)" % clock.bpm) except KeyboardInterrupt: pass finally: m_in.close_port() del m_in
def main(args=None): ap = argparse.ArgumentParser(usage=__doc__.splitlines()[0]) ap.add_argument('-p', '--port', help="MIDI input port index / name.") ap.add_argument('bpm', type=int, default=120, help="Starting BPM.") args = ap.parse_args(args) clock = MIDIClockReceiver(args.bpm) try: m_in, port_name = open_midiinput(args.port) except (EOFError, KeyboardInterrupt): return 1 m_in.set_callback(clock) # Important: enable reception of MIDI Clock messages (status 0xF8) m_in.ignore_types(timing=False) try: print("Waiting for clock sync...") while True: time.sleep(1) if clock.running: if clock.sync: print("%.2f bpm" % clock.bpm) else: print("%.2f bpm (no sync)" % clock.bpm) except KeyboardInterrupt: pass finally: m_in.close_port() del m_in
def script_update(settings): global currentMidiPort global midiin global midiParams askedPort = obs.obs_data_get_string(settings, "midiDevice") if currentMidiPort != askedPort: if currentMidiPort != "": midiin.close_port() currentMidiPort = "" ok = True if askedPort != "": try: midiin, port_name = open_midiinput(askedPort) midiin.set_callback(MidiInputHandler(port_name)) except (EOFError, KeyboardInterrupt): print("Meh :/") ok = False if ok: currentMidiPort = askedPort midiParams[0] = obs.obs_data_get_string(settings, "transitionMidiType") midiParams[1] = obs.obs_data_get_int(settings, "transitionMidiAddress") midiParams[2] = obs.obs_data_get_string(settings, "scenesMidiType") midiParams[3] = obs.obs_data_get_int(settings, "scenesMidiAddress") midiParams[4] = obs.obs_data_get_string(settings, "transitionsMidiType") midiParams[5] = obs.obs_data_get_int(settings, "transitionsMidiAddress") midiParams[6] = obs.obs_data_get_bool(settings, "logMidiInput")
def __init__(self, port=None, always_recording=True): """ Args: port (int, optional): specifies a midi device/port option. Only useful if you already know how your available midi ports will be listed. always_recording (bool): """ self.always_recording = always_recording self.currently_recording = always_recording self.time_to_stop_recording = None self.history = [] # collects note history as MidiKeyPress objects self._port = port self._wallclock = time.time() self.debug_mode = False # self.log = logging.getLogger('midiin_callback') # logging.basicConfig(level=logging.DEBUG) # Prompts user for MIDI input port, unless a valid port number or name # is given as the first argument on the command line. # API backend defaults to ALSA on Linux. try: self._midiin, self._port = open_midiinput(self._port) except (EOFError, KeyboardInterrupt): sys.exit() # print("Attaching MIDI input callback handler.") self._midiin.set_callback(self._midi_input_handler)
def main(): # rtmidi inisialisation port = 1 midiin, port_name = open_midiinput(port) midiin.set_callback(MidiInputHandler(port_name)) # Pygame initialisation pygame.init() display = (800, 600) pygame.display.set_mode(display, DOUBLEBUF | OPENGL) # OpenGL initialisation gluPerspective(45, display[0] / display[1], 0.1, 50.0) # FOV, viewing angle, clipping distance glTranslatef(0.0, 0.0, -15.0) glRotatef(0, 0, 0, 0) # main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() midiin.close_port() del midiin quit() update_rotation() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(int(1000 / FRAME_RATE_CAP))
def main(): # Prompts user for MIDI input port, unless a valid port number or name # is given as the first argument on the command line. # API backend defaults to ALSA on Linux. port = sys.argv[1] if len(sys.argv) > 1 else None try: midiin, port_name = open_midiinput(port) except (EOFError, KeyboardInterrupt): sys.exit() print("Attaching MIDI input callback handler.") midiin.set_callback(MidiInputHandler(port_name)) print("Entering main loop. Press Control-C to exit.") try: # Just wait for keyboard interrupt, # everything else is handled via the input callback. while True: time.sleep(1) except KeyboardInterrupt: print('') finally: print("Exit.") midiin.close_port() del midiin
def __init__(self, port): self.port = port try: self.midiin, port_name = open_midiinput(port) except (EOFError, KeyboardInterrupt): print("MIDI port not available") return
def open_midiin(port): """ Return a MIDI in port instance for the given port. :param port: Port to be opened, 0-n. :return: """ midiin, name = open_midiinput(port=port) return midiin
def set_midiin(port): global midiin if port != "None": #midiin.open_port(0) midiin.close_port() #midiin, portname = open_midiport(port=port, type_="input") midiin, portname = open_midiinput(port=port) print("Input: " + portname)
def __init__(self, port, directory, debug=False, overwrite=True): self._directory = directory self._debug = debug self._overwrite = overwrite self._fn_index = 1 self.sysex_count = 0 self._midiin, name = open_midiinput(port) self._midiin.ignore_types(sysex=False)
def open_midi_device(): out_port = sys.argv[1] if len(sys.argv) > 1 else None in_port = sys.argv[2] if len(sys.argv) > 2 else None try: midiout, port_name = open_midioutput(out_port) midiin, _ = open_midiinput(in_port) except (EOFError, KeyboardInterrupt): sys.exit() return midiout, midiin, port_name
def __init__(self, host, port, midi_port, topicprefix): self.topicprefix = topicprefix self.midiin, port_name = midi.open_midiinput(midi_port) print("listening to midi device", port_name) self.midiin.set_callback(self.on_midi_event) print("connecting and sending msgs to", host, port) self.mqtt = mqtt.Client() self.mqtt.connect(host, port)
def __init__(self, fifo_length): # Must physically connect the MIDI device to this port. port = 1 # The FIFO allows multiple or no MIDI data in between each time the # server runs. The driver writes the FIFO and provides a method # for the server to read the FIFO. self.fifo = fifo.Fifo(fifo_length) self.midi_in, port_name = rtmu.open_midiinput(port) self.midi_in.set_callback(MidiCallback(port_name, self.fifo)) self.tell_me_everything(port_name)
def set_midiin(self, context): global midi_in_pt port = midi_in_pt if g_vars.midiin.is_port_open(): g_vars.midiin.close_port() g_vars.midiin.delete() g_vars.midiin = rtmidi.MidiIn() if port != "None": if port != "Virtual Port": g_vars.midiin, portname = open_midiinput(port=port, interactive=False, client_name="Blender In") else: g_vars.midiin, portname = open_midiinput( use_virtual=True, interactive=False, client_name="Blender Virtual In") print("MIDI Input: " + portname)
def main(args=None): """Main program function. Parses command line (parsed via ``args`` or from ``sys.argv``), detects and optionally lists MIDI input ports, opens given MIDI input port, and attaches MIDI input handler object. """ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) padd = parser.add_argument padd('-b', '--backend', choices=sorted(BACKEND_MAP), help='MIDI backend API (default: OS dependant)') padd('-p', '--port', help='MIDI input port name or number (default: open virtual input)') padd('-v', '--verbose', action="store_true", help='verbose output') padd(dest='config', metavar="CONFIG", help='Configuration file in YAML syntax.') args = parser.parse_args(args if args is not None else sys.argv[1:]) logging.basicConfig(format="%(name)s: %(levelname)s - %(message)s", level=logging.DEBUG if args.verbose else logging.INFO) try: midiin, port_name = open_midiinput(args.port, use_virtual=True, api=BACKEND_MAP.get( args.backend, rtmidi.API_UNSPECIFIED), client_name='midi2command', port_name='MIDI input') except (IOError, ValueError) as exc: return "Could not open MIDI input: %s" % exc except (EOFError, KeyboardInterrupt): return log.debug("Attaching MIDI input callback handler.") midiin.set_callback(MidiInputHandler(port_name, args.config)) log.info("Entering main loop. Press Control-C to exit.") try: # just wait for keyboard interrupt in main thread while True: time.sleep(1) except KeyboardInterrupt: print('') finally: midiin.close_port() del midiin
def __init__(self, callback = print, callback2= print, callback3 = print, callback4 = print): self.callback = callback self.callback2 = callback2 self.callback3 = callback3 self.callback4 = callback4 self.last_note = 0 self.current_notes = set() self.on = True self.midiin, port_name = open_midiinput(0, api=0) self.last_note_fret = {0:10, 1:10, 2:10, 3:10, 4:10, 5:10} self.midiin.ignore_types(sysex=False)
def connect(self, inport, outport): try: self.midiin, self.inport_name = open_midiinput(inport) self.midiout, self.outport_name = open_midioutput(outport) return True except OSError: print("there is no midi device") sys.exit() return False except (EOFError, KeyboardInterrupt): sys.exit() return False
def main(args=None): """Main program function. Parses command line (parsed via ``args`` or from ``sys.argv``), detects and optionally lists MIDI input ports, opens given MIDI input port, and attaches MIDI input handler object. """ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) padd = parser.add_argument padd('-b', '--backend', choices=sorted(BACKEND_MAP), help='MIDI backend API (default: OS dependant)') padd('-p', '--port', help='MIDI input port name or number (default: open virtual input)') padd('-v', '--verbose', action="store_true", help='verbose output') padd(dest='config', metavar="CONFIG", help='Configuration file in YAML syntax.') args = parser.parse_args(args if args is not None else sys.argv[1:]) logging.basicConfig(format="%(name)s: %(levelname)s - %(message)s", level=logging.DEBUG if args.verbose else logging.INFO) try: midiin, port_name = open_midiinput( args.port, use_virtual=True, api=BACKEND_MAP.get(args.backend, rtmidi.API_UNSPECIFIED), client_name='midi2command', port_name='MIDI input') except (IOError, ValueError) as exc: return "Could not open MIDI input: %s" % exc except (EOFError, KeyboardInterrupt): return log.debug("Attaching MIDI input callback handler.") midiin.set_callback(MidiInputHandler(port_name, args.config)) log.info("Entering main loop. Press Control-C to exit.") try: # just wait for keyboard interrupt in main thread while True: time.sleep(1) except KeyboardInterrupt: print('') finally: midiin.close_port() del midiin
def run(self): midi_input, _port_name = open_midiinput(port="aurora") midi_input.set_callback(self.callback) self.led_index = 0 self.key = 0 self.km = KeyMapper() self.m = dict(self.km.km) self.compositor = Compositor() self.s = connect() while True: time.sleep(0.05) frame = self.compositor.new_frame() wire_event = frame.as_state_event() payload = wire_event.serialize().encode() self.s.sendall(payload)
def main(args=None): decoder = RPNDecoder() m_in, port_name = open_midiinput(args[0] if args else None) m_in.set_callback(decoder) try: while True: rpn = decoder.last_changed if rpn: print("RPN %i: %i" % (rpn, decoder.values[rpn])) decoder.last_changed = None time.sleep(0.1) except KeyboardInterrupt: pass
def main(args=None): decoder = RPNDecoder() m_in, port_name = open_midiinput(args[0] if args else None) m_in.set_callback(decoder) try: while True: rpn = decoder.last_changed if rpn: print(("RPN %i: %i" % (rpn, decoder.values[rpn]))) decoder.last_changed = None time.sleep(0.1) except KeyboardInterrupt: pass
def setup_input(self): api_in = MidiIn() api_in.ignore_types(sysex=False) port_in = self.get_mixer_port(api_in) try: midi_in, port_name = open_midiinput(port_in, interactive=False) except InvalidPortError: return except NoDevicesError: return midi_in.ignore_types(sysex=False) midi_in.set_callback(self.listener) self.api_in = api_in self.input = midi_in return port_name
def start_midi_listener(port_number_or_device_name, callback_function, clock): """ Start a midi listener on a given port (or for the given device) :param port_number_or_device_name: either the port number to be used, or an device name for which the port number will be determined. (Fuzzy string matching is used to pick the device with closest name.) :type port_number_or_device_name: int or str :param callback_function: the callback function used when a new midi event arrives. Should take either one argument (the midi message) or two arguments (the midi message, and the dt since the last message) :param clock: the clock to rouse when this callback operates :type clock: Clock """ port_number = get_port_number_of_midi_device(port_number_or_device_name, "input") \ if isinstance(port_number_or_device_name, str) else port_number_or_device_name if port_number is None: raise ValueError("Could not find matching MIDI device.") elif port_number not in (x[0] for x in get_available_midi_input_devices()): raise ValueError("Invalid port number for midi listener.") callback_function_signature = inspect.signature(callback_function) if not 1 <= len(callback_function_signature.parameters) <= 2: raise AttributeError( "MIDI callback function should take either one argument (the midi message) or " "two arguments (the midi message and the time since the last message)." ) callback_accepts_dt = len(callback_function_signature.parameters) == 2 from rtmidi.midiutil import open_midiinput midi_in, _ = open_midiinput(port_number) @functools.wraps(callback_function) def callback_wrapper(message, data=None): clock.rouse_and_hold() threading.current_thread().__clock__ = clock if callback_accepts_dt: callback_function(message[0], message[1]) else: callback_function(message[0]) threading.current_thread().__clock__ = None clock.release_from_suspension() midi_in.set_callback(callback_wrapper) return midi_in
def openPort(self, askedPort): if self.currentMidiPort == askedPort: return if self.midiin: self.midiin.close_port(); self.currentMidiPort = "" if askedPort == "": return try: self.midiin, port_name = open_midiinput(askedPort, use_virtual=True) self.midiin.set_callback(self.onMidi) print("connected to " + port_name) self.currentMidiPort = askedPort except (EOFError, KeyboardInterrupt): print("Failed to open port")
def __init__(self, name="Unnamed Port", interactive=False, auto_start=True): self.name = name if interactive: self.output, self.outname = open_midioutput(select_port("output")) self.input, self.inname = open_midiinput(select_port("input")) # The port's main_loop is supposed to run in its own thread. It is only started if # the object is constructed with auto_start = True or if the start method is called self.thread = Thread(target=self.main_loop, daemon=True) # Listeners to this Device register Queue objects to be informed of Events self.listener_qs = set() if auto_start: if not (self.input and self.output): print("Could not start the Device thread without any input or output configured") else: self.start()
def midiSetup(self): # Prompts user for MIDI input port, unless a valid port number or name # is given as the first argument on the command line. # API backend defaults to ALSA on Linux. # print("input value: ") port = sys.argv[1] if len(sys.argv) > 1 else None try: midiin, port_name = open_midiinput(port) except (EOFError, KeyboardInterrupt): sys.exit() try: midiout, port_name = open_midioutput(port) except (EOFError, KeyboardInterrupt): sys.exit() return midiin, midiout
def main(): """main entrypoint""" try: midi_in, port_name = open_midiinput(PORT) except (EOFError, KeyboardInterrupt): sys.exit(0) midi_in.set_callback(visualizer.MidiInputAnalysisHandler(port_name)) print("Press Control-C to exit.") try: while True: time.sleep(1) except KeyboardInterrupt: print('') finally: midi_in.close_port() del midi_in
def main(args=None): """Save revceived sysex message to directory given on command line.""" parser = argparse.ArgumentParser(description=__doc__) padd = parser.add_argument padd('-o', '--outdir', default=os.getcwd(), help="Output directory (default: current working directory).") padd('-p', '--port', help='MIDI output port number (default: ask)') padd('-v', '--verbose', action="store_true", help='verbose output') args = parser.parse_args(args) logging.basicConfig(format="%(name)s: %(levelname)s - %(message)s", level=logging.DEBUG if args.verbose else logging.INFO) try: midiin, port = open_midiinput(args.port) except IOError as exc: log.error(exc) return 1 except (EOFError, KeyboardInterrupt): return 0 ss = SysexSaver(port, args.outdir, args.verbose) log.debug("Attaching MIDI input callback handler.") midiin.set_callback(ss) log.debug("Enabling reception of sysex messages.") midiin.ignore_types(sysex=False) log.info("Uploading to: %s", args.outdir) log.info("Waiting for sysex reception. Press Control-C to exit.") try: # just wait for keyboard interrupt in main thread while True: time.sleep(1) except KeyboardInterrupt: print('') finally: log.debug("Exit.") midiin.close_port() del midiin
def main(args): midiin, _ = open_midiinput(args[0] if args else None) # record Modulation, Volume and Expression CC events handler = MidiInHandler(channel=1, controllers=CONTROLLERS) midiin.set_callback(handler) try: with midiin: while True: for cc in CONTROLLERS: print("CC #%i: %s" % (cc, handler.get(cc))) print("--- ") time.sleep(1) except KeyboardInterrupt: pass finally: del midiin
def main(): s = connect() print(f"Connected. Starting handlers.") eh = EventHandler(s) midi_input, _port_name = open_midiinput(port="aurora") midi_input.set_callback(eh.on_midi_event) print(midi_input) try: while True: time.sleep(0.05) eh.on_parsed_event(mido.Message("clock")) except KeyboardInterrupt: pass finally: midi_input.close_port() del midi_input
10: True, pk.BUTTON_X: True, pk.BUTTON_Y: True, pk.BUTTON_PEDAL: True, pk.BUTTON_NOTE_CC: True, pk.BUTTON_SW_TYPE: True, pk.BUTTON_REL_VAL: True, pk.BUTTON_VELOCITY: True, pk.BUTTON_PORT: True })) raw_input('Press enter to demonstrate input handling (then enter again to exit this example).') midi_in, _ = open_midiinput( INPUT_MIDI_PORT, api=rtmidi.API_UNIX_JACK, client_name="padkontrol", port_name="MIDI In") pk_print = PadKontrolPrint() def midi_in_callback(message, data): sysex_buffer = [] for byte in message[0]: sysex_buffer.append(byte) if (byte == 0xF7): pk_print.process_sysex(sysex_buffer) del sysex_buffer[:] # empty list midi_in.ignore_types(False, False, False)
self.port = port self._wallclock = time.time() def __call__(self, event, data=None): message, deltatime = event self._wallclock += deltatime print("[%s] @%0.6f %r" % (self.port, self._wallclock, message)) # Prompts user for MIDI input port, unless a valid port number or name # is given as the first argument on the command line. # API backend defaults to ALSA on Linux. port = sys.argv[1] if len(sys.argv) > 1 else None try: midiin, port_name = open_midiinput(port) except (EOFError, KeyboardInterrupt): sys.exit() print("Attaching MIDI input callback handler.") midiin.set_callback(MidiInputHandler(port_name)) print("Entering main loop. Press Control-C to exit.") try: # Just wait for keyboard interrupt, # everything else is handled via the input callback. while True: time.sleep(1) except KeyboardInterrupt: print('') finally:
import time import liblo from rtmidi.midiconstants import NOTE_ON from rtmidi.midiutil import open_midiinput def midiin_callback(event, data=None): message, deltatime = event if message[0] & 0xF0 == NOTE_ON: status, note, velocity = message channel = (status & 0xF) + 1 liblo.send( ('localhost', 9001), '/midi/%i/noteon' % channel, note, velocity) # Prompts user for MIDI input port, defaulting to ALSA on Linux try: port = sys.argv[1] if len(sys.argv) > 1 else None with open_midiinput(port, client_name='noteon2osc')[0] as midiin: midiin.set_callback(midiin_callback) while True: time.sleep(1) except (EOFError, KeyboardInterrupt): print("Bye.")