def start_midi_stream(file_name, display): last_note = int(round(time.time() * 1000)) mido.get_output_names() port_name = mido.get_input_names()[0] print('Starting on port: ' + port_name) with MidiFile() as mid: track = MidiTrack() try: print("Waiting For Keyboard Input ... ") with mido.open_input(port_name) as inport: for msg in inport: now = int(round(time.time() * 1000)) msg.time = now - last_note last_note = now if hasattr(msg, 'velocity') and msg.velocity == 0: msg = Message('note_off', note=msg.note, velocity=msg.velocity, time=msg.time) track.append(msg) if display: print(msg) except KeyboardInterrupt: if file_name: print("\nStopping and saving file ... ") else: print("\nStopping ...") finally: if file_name: print(file_name) mid.tracks.append(track) mid.save(file_name) print("File Saved!") print("File Location: " + file_name) else: print("Done!")
def main(): output_names = mido.get_output_names() for index, each in enumerate(output_names): print('out id: %d name: %s' % (index, each)) input_names = mido.get_input_names() for index, each in enumerate(input_names): print('in id: %d name: %s' % (index, each))
def open_output(self): if self.backend == 'mido': if self.debug>0: print('------ OUTPUT ------') for port in mido.get_output_names(): print(port) print('-------------------------') try: self.outputport = mido.open_output(self.config.get('midi', 'device')) print "Connected to MIDI output" except: print "Error: cannot connect to MIDI output" raise RuntimeError("Error: cannot connect to MIDI output") elif self.backend == 'midiosc': try: self.outputport = OSC.OSCClient() self.outputport.connect((self.config.get('midi','hostname'), self.config.getint('midi','port'))) print "Connected to OSC server" except: print "Error: cannot connect to OSC server" raise RuntimeErrror("cannot connect to OSC server") else: print 'Error: unsupported backend: ' + self.backend raise RuntimeError('unsupported backend: ' + self.backend)
def __init__(self, _save_path, songfile, _plyr_ctrls): super(PlayerThread, self).__init__() self.name = 'Player' self.stoprequest = threading.Event() self.plyr_ctrls = _plyr_ctrls self.chan_roles = [0 for i in range(10)] self.plyr_ctrls['songfile'] = songfile self.midifile = MidiFile(_save_path + songfile) # 0 - drum fill self.counter = [0 for i in range(4)] self.wt = WolfTonesSong() self.save_path = _save_path self.load_song(songfile) self.alt_meas = [] #get the portname (system specific) env = socket.gethostname() if(env == 'record_synth'): names = str(mido.get_output_names()) ports = names.split(',') sobj = re.search(r'Synth input port \(\d*:0\)', ports[0], flags=0) portname = sobj.group() if(env == 'colinsullivan.me'): #dummy port for testing on a headless server with no audio portname = 'Midi Through:Midi Through Port-0 14:0' self.outport = mido.open_output(portname, autoreset=True)
def command(args): import mido ports = mido.get_output_names() print(len(ports), 'outputs:') for port in ports: print('-', port)
def list_ports(self): """ List MIDI ports """ ports = get_output_names() if len(ports) < 1: self.log.error('No open MIDI ports') sys.exit(1) print 'Open Ports' print '----------' print '\n'.join(ports)
def open_pair(input, output): if not isinstance(input, mido.ports.BaseInput): state.inp = mido.open_input([i for i in mido.get_input_names() if i.lower().startswith(input.lower())][0]) else: state.inp = input if not isinstance(output, mido.ports.BaseOutput): state.out = mido.open_output([i for i in mido.get_output_names() if i.lower().startswith(output.lower())][0]) else: state.out = output setup_threads() state.metronome = Metronome()
def _open_output(self, port): if self._out_port is None: try: self._out_port = mido.open_output(port) except IOError: print "Couldn't open output port '%s'. The following MIDI ports are available:" % port for p in mido.get_output_names(): print "'%s'" % p raise else: assert self._out_port.name == port return self._out_port
def __init__(self): port_names = mido.get_output_names() if not port_names: raise IndexError("No MIDI output ports found") if len(port_names) == 1: idx = 0 logging.info("Choosing MIDI output port %s", port_names[0]) else: print("MIDI output ports:") for (idx, name) in enumerate(port_names): print("{}. {}".format(idx, name)) idx = int(raw_input("Which MIDI output port? ")) assert 0 <= idx < len(port_names) self.midi_out = mido.open_output(port_names[idx])
def process_appl_cmd(self, appl_cmd): cmd_type, payload = appl_cmd if cmd_type == 'quit': self.running = False return "Show application is quitting." elif cmd_type == 'load': self.load(payload) return "Loaded show {}".format(payload) elif cmd_type == 'save': self.save(payload) return "Saved show {}".format(payload) elif cmd_type == 'list_midi': return mido.get_output_names() return None
def __init__(self, target=MIDIOUT_DEFAULT): self.midi = None self.debug = False ports = mido.get_output_names() if len(ports) == 0: raise Exception("No MIDI output ports found") for name in ports: if name == target: isobar.log("Found MIDI output (%s)" % name) self.midi = mido.open_output(name) if self.midi is None: print "Could not find MIDI target %s, using default" % target self.midi = mido.open_output()
def main(screen): main_options = Options() if main_options.settings['writeinifile']: main_options.write_options_ini() quit() elif main_options.settings['listmidiports']: print("\nAvailable MIDI ports:") print("\n".join(mido.get_output_names())) print("") quit() #screen.clear() midi_receiver = MidiReceiver(main_options) #screen.refresh() midi_receiver.start()
def main(unused_argv): if FLAGS.list: print "Input ports: '" + "', '".join(mido.get_input_names()) + "'" print "Output ports: '" + "', '".join(mido.get_output_names()) + "'" return if FLAGS.input_port is None or FLAGS.output_port is None: print '--inport_port and --output_port must be specified.' return if (FLAGS.start_capture_control_number == FLAGS.stop_capture_control_number and (FLAGS.start_capture_control_value == FLAGS.stop_capture_control_value or FLAGS.start_capture_control_value is None or FLAGS.stop_capture_control_value is None)): print('If using the same number for --start_capture_control_number and ' '--stop_capture_control_number, --start_capture_control_value and ' '--stop_capture_control_value must both be defined and unique.') return if not 0 <= FLAGS.metronome_playback_velocity <= 127: print 'The metronome_playback_velocity must be an integer between 0 and 127' return generator = Generator( FLAGS.generator_name, FLAGS.num_bars_to_generate, ast.literal_eval(FLAGS.hparams if FLAGS.hparams else '{}'), FLAGS.checkpoint) hub = MonoMidiHub(FLAGS.input_port, FLAGS.output_port) stdout_write_and_flush('Waiting for start control signal...\n') while True: hub.wait_for_control_signal(FLAGS.start_capture_control_number, FLAGS.start_capture_control_value) hub.stop_playback() hub.start_capture(FLAGS.bpm) stdout_write_and_flush('Capturing notes until stop control signal...') hub.wait_for_control_signal(FLAGS.stop_capture_control_number, FLAGS.stop_capture_control_value) captured_sequence = hub.stop_capture() stdout_write_and_flush('Generating response...') generated_sequence = generator.generate_melody(captured_sequence) stdout_write_and_flush('Done\n') hub.start_playback(generated_sequence, FLAGS.metronome_playback_velocity)
def __init__(self, options): self.midi_processor = MidiProcessor(options) if options.settings['midiout']: if options.settings['outport'] == 'default': available_ports = mido.get_output_names() if available_ports: options.settings['outport'] = available_ports[0] else: options.settings['outport'] = "" if options.settings['outport']: self.midi_processor.midi_outport = mido.open_output( options.settings['outport']) if options.settings['getbeats'] == 'True': self.beat_finder = BeatFinder(options) self.beat_finder.midi_processor = self.midi_processor else: self.beat_finder = None if options.settings['gettempo'] == 'True': self.tempo_finder = TempoFinder(options) self.tempo_finder.midi_processor = self.midi_processor else: self.tempo_finder = None if options.settings['getrms'] == 'True': self.rms_finder = RMSFinder(options) self.rms_finder.midi_processor = self.midi_processor else: self.rms_finder = None if options.settings['getfrequencies'] == 'True': self.frequencies_finder = FrequenciesFinder(options) self.frequencies_finder.midi_processor = self.midi_processor else: self.frequencies_finder = None if options.settings['getpitch'] == 'True': self.pitch_finder = PitchFinder(options) self.pitch_finder.midi_processor = self.midi_processor else: self.pitch_finder = None if options.settings['inputdevice'] == 'default': options.settings['inputdevice'] = sd.default.device['input'] self.input_device = options.settings['inputdevice'] self.channels = int(options.settings['channels']) self.blocksize = int(options.settings['framesize']) self.samplerate = int(options.settings['samplerate'])
def main(): pattern_options = ', '.join(arpeggiators.keys()) parser = argparse.ArgumentParser() parser.add_argument('pattern', help='Arpeggiator pattern to apply to notes. options: {}'.format(pattern_options)) parser.add_argument('bpm', type=int, help='Beats Per Minute to run arpeggio. Notes are played as quarter notes.') parser.add_argument('notes', help='Comma separated list of semitones up to an octave above the root (0-12)') parser.add_argument('--fakeoutport', dest='fakeoutport', action='store_true', help='No output port. Print MIDI messages to console for debugging.') args = parser.parse_args() # TODO validate pattern_name = args.pattern notes = [int(note) for note in args.notes.split(',')] bpm = args.bpm if args.fakeoutport: outport = PrintPort() else: # ask which interface to use outputs = mido.get_output_names() if len(outputs) < 1: sys.stderr.write("Error: No MIDI output interfaces detected.\n") exit(errno.ENODEV) print "MIDI Output Interfaces:" for i, interface in enumerate(outputs): print "\t{}) {}".format(i + 1, interface) print "Enter the number of the interface your Whammy is connected to:", raw_value = raw_input() output_index = int(raw_value) - 1 outport = mido.open_output(outputs[output_index]) whammy_interface = whammy.WhammyInterface(outport) whammy_arp = whammy.WhammyArp(whammy_interface, notes, pattern_name, bpm) while (True): whammy_arp.play_next_step()
def __init__(self): cmd.Cmd.__init__(self) print "Color Organist" print "Using midi port {}.".format(mido.get_output_names()[0]) # TODO: add port selection, mido makes this tricky because it doesn't # play nicely with threads. # #while port is None: # print "Please select a midi port." # print str(mido.get_output_names()) + '\n' # port = readline() print "Starting empty show." self.cmd_queue = Queue() self.resp_queue = Queue() show = Show(60., self.cmd_queue, self.resp_queue) self.show_thread = Thread(target=show.run) self.show_thread.start() print "Show is running." self.cmdloop()
def initialize_MIDI_inout(): """Initialize MIDI input and output ports using RTMIDI through mido We will go ahead and initialize all four of the input ports from the MIDIPLUS interface, plus the output port to the console. """ # select rtmidi as our backend mido.set_backend('mido.backends.rtmidi') # print "Backend selected is %s " % mido.backend # Enumerate the available port names outports = mido.get_output_names() # Now try to pick the right port to output on. # If we're in the deployed configuration, it's a MIO adapter. outport = None for name in outports: if re.match(r'mio', name): try: outport = mido.open_output(name) break except: pass if not outport: print("Unable to open the MIO MIDI output port.") sys.exit(1) # Now locate the ports of the MIDIPLUS interface and open them for input. port_prefix = 'MIDI4x4.*:' inports = [] for port in ('0', '1', '2', '3'): inports.append(open_midi_input_port(port_prefix + port)) if len(inports) != 4: print("Unable to open MIDI input ports. Is the MIDIPLUS connected?") sys.exit(1) return (inports, outport)
def initialize_MIDI_out(): """Initialize a MIDI output port using RTMIDI through mido """ # select rtmidi as our backend mido.set_backend('mido.backends.rtmidi') # print "Backend selected is %s " % mido.backend # Enumerate the available port names outports = mido.get_output_names() # Now try to pick the right port to output on. # If we're in the deployed configuration, it's a MIO adapter, but # if we're in the lab, it might be something else. # In either event, there might be more than one matching adapter! # In that case, we'll punt and take the first one we find. out = None for name in outports: if re.match(r'mio', name): try: out = mido.open_output(name) break except: pass if not out: for name in outports: try: out = mido.open_output(name) break except: pass if not out: print("Sorry, unable to open any MIDI output port.") sys.exit(1) return out
def select_midi_output_port(self): acc = [] for p in mido.get_output_names(): acc.append(p) while True: print() mrn = self.config["midi-transmitter-name"] for n, p in enumerate(acc): print(" [%d] %s" % (n+1, p)) print() print("\nPress [Enter] to select default") usr = infn("Select MIDI output port (%s) > " % mrn) if not usr: break try: n = int(usr) if 0 < n <= len(acc): mrn = acc[n-1] self.config["midi-transmitter-name"] = mrn break else: raise ValueError() except ValueError: print("ERROR")
wait = False #PAUSE FOR WHEN NOTE DROPS TOO FAR #mapping = {:1,:2,:3,:4,60:5,:6,:7,:8,:9,:10} notespeed = 5 #speed at which notes fall/rise '''FIRE UP TiMIDIty++''' '''def starttimidity(): os.system('timidity -iAqq') def startstarttimidity(): timiditythread = Thread(target = starttimidity) timiditythread.daemon = True timiditythread.start() startstarttimidity()''' mido.set_backend('mido.backends.pygame') port = mido.open_output(mido.get_output_names()[1]) pygame.init() '''TITLESCREENS''' def readtitle(): global screenw, screenh, screen while True: screen.fill((0, 0, 0)) titlefont = pygame.font.Font(None, 300) normalfont = pygame.font.Font(None, 100) screen.blit(titlefont.render('Learn', 1, (100, 100, 100)), (screenw * 0.1 + 20, screenh * 0.25 + 20)) screen.blit(titlefont.render('Learn', 1, (100, 255, 100)), (screenw * 0.1, screenh * 0.25)) pygame.display.flip()
def list_devices(): return { 'input': mido.get_input_names(), 'output': mido.get_output_names(), }
def get_available_output_ports(): """Returns a list of available output MIDI ports.""" return mido.get_output_names()
pass if __name__ == '__main__': # Startup loop. Populates options and starts up ProcessAudio. # # Loads the options class, and if it was one the special cases like # writing the inifile or printing out the midi and sound device # information, do that then quit. # # Otherwise, start the ProcessAudio class and get out of the way. main_options = Options() if main_options.settings['writeinifile']: main_options.write_options_ini() quit() elif main_options.settings['listsounddevices'] or main_options.settings[ 'listmidiports']: if main_options.settings['listsounddevices']: print("\nAvailable sound devices:") print(sd.query_devices()) if main_options.settings['listmidiports']: print("\nAvailable MIDI ports:") print("\n".join(mido.get_output_names())) print("") quit() print("Control-C to quit") process_audio = ProcessAudio(main_options) process_audio.start() while True: time.sleep(.1)
def getMidiOutputs(): return mido.get_output_names()
def main(): parser = argparse.ArgumentParser(description='MoppyPlayer %s' % version.FULL) parser.add_argument("-f", "--file", default=None, help="MIDI file to play") parser.add_argument("-p", "--port", default=None, help="Port to use (sysfs, serial or midiport)") parser.add_argument("-l", "--portlist", action="store_true", default=False, help="List available MIDI ports") parser.add_argument("--serdev", default="/dev/ttyUSB0", help="Serial device to use when port 'serial' " + "is selected") parser.add_argument("--chmax", default=4, type=int, help="Maximum number of channels") parser.add_argument("--choptimize", action="store_true", default=False, help="Try to optimize channel allocation") parser.add_argument("--chmirror", action="store_true", default=False, help="Mirror channels") parser.add_argument("--nopercussions", action="store_true", default=False, help="Remove percussions channel (#10)") parser.add_argument("--octoptimize", action="store_true", default=False, help="Try to optimize octaves") parser.add_argument("--optimize", action="store_true", default=False, help="Enable all optimizations") args = parser.parse_args() if args.portlist: port_names = mido.get_output_names() for port in port_names: print(port) exit(0) if args.optimize: args.choptimize = True args.octoptimize = True args.nopercussions = True if args.port == "sysfs": port = MoppySysfsPort() elif args.port == "serial": port = SerialPort(args.serdev, 9600) elif args.port is None: port = NullPort() else: port = mido.open_output(args.port) if args.file is not None: if args.nopercussions: ch_filter = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15] else: ch_filter = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] vp = VisualPlayer(port, args.file, args.chmax, ch_filter, args.choptimize, args.chmirror, args.octoptimize) vp.play()
def _build_south_panel(self, south): self._midi_input_ports = mido.get_input_names() self._midi_output_ports = mido.get_output_names() port_rows = max(len(self._midi_input_ports), len(self._midi_output_ports)) init_id = self.config.global_osc_id() init_host = self.config["host"] init_port = self.config["port"] init_client = self.config["client"] init_client_port = self.config["client_port"] init_input = self.config["midi-receiver-name"] init_output = self.config["midi-transmitter-name"] self.var_id = StringVar() self.var_host = StringVar() self.var_port = StringVar() self.var_client = StringVar() self.var_client_port = StringVar() self.var_input = StringVar() self.var_output = StringVar() def restore_defaults(): self.var_id.set(init_id) self.var_host.set(init_host) self.var_port.set(init_port) self.var_client.set(init_client) self.var_client_port.set(init_client_port) self.var_input.set(init_input) self.var_output.set(init_output) restore_defaults() e_id = factory.entry(south, self.var_id) e_host = factory.entry(south, self.var_host) e_port = factory.entry(south, self.var_port) e_client = factory.entry(south, self.var_client) e_client_port = factory.entry(south, self.var_client_port) #factory.padding_label(south).grid(row=0, column=0, ipadx=8, ipady=8) e_id.grid(row=1, column=1, columnspan=2) e_host.grid(row=2, column=1, columnspan=2) e_port.grid(row=2, column=5, columnspan=2) e_client.grid(row=3, column=1, columnspan=2) e_client_port.grid(row=3, column=5, columnspan=2) port_count = max(len(self._midi_input_ports), len(self._midi_output_ports)) lab_id = factory.label(south, "OSC ID") lab_host = factory.label(south, "Host") lab_host_port = factory.label(south, "Port") lab_client = factory.label(south, "Client") lab_client_port = factory.label(south, "Port") lab_midi_input = factory.label(south, "MIDI Input") lab_midi_output = factory.label(south, "MIDI Output") # factory.padding_label(south).grid(row=4, column=3, ipadx=8, ipady=8) lab_id.grid(row=1, column=0, columnspan=1, ipadx=8, ipady=8) lab_host.grid(row=2, column=0, columnspan=1) lab_host_port.grid(row=3, column=4, columnspan=1, ipadx=4) lab_client.grid(row=3, column=0, columnspan=1) lab_client_port.grid(row=3, column=4, columnspan=1) lab_midi_input.grid(row=5, column=1, columnspan=2, ipady=8) lab_midi_output.grid(row=5, column=5, columnspan=2, ipady=8) for n,p in enumerate(self._midi_input_ports): rb = factory.radio(south, str(p), self.var_input, str(p)) rb.grid(row=n+6, column=1, sticky="W") for n,p in enumerate(self._midi_output_ports): rb = factory.radio(south, str(p), self.var_output, str(p)) rb.grid(row=n+6, column=5, sticky="W") factory.padding_label(south).grid(row=0, column=7, ipadx=36) #b_restore = factory.button(south, "Restore", command=restore_defaults) b_continue = factory.button(south, "Continue", command=self.accept) b_help = factory.help_button(south) b_help.config(command=self.display_help) row = port_count + 6 #b_restore.grid(row=row, column=1, sticky="EW", pady=16) b_continue.grid(row=row, column=1, sticky="EW", pady=16) b_help.grid(row=row, column=3, padx=8, sticky="W") self.lab_warning = factory.label(south, "") self.lab_warning.config(foreground=factory.pallet("warning-fg")) self.lab_warning.grid(row=6, column=7, sticky="EW", columnspan=2, rowspan=4)
def get_port(): port_list = mido.get_output_names() print('Available MIDI ports are \n') for name in range(0, len(port_list)): print('%s' % name, port_list[name]) return port_list[int(input('Choose port by number: '))]
def openOut(deviceName): outputPort = chooseDevice(mido.get_output_names(), deviceName) if outputPort: return mido.open_output(outputPort) else: return None
import mido print('Input ports:') for item in mido.get_input_names(): print("\t{}".format(item)) print('Output ports:') for item in mido.get_output_names(): print("\t{}".format(item))
def main(port): if (port is None): print ('Available MIDI ports') print (mido.get_output_names()) else: listen(port)
def available_ports(cls, output=True): if output: return mido.get_output_names() return mido.get_input_names()
def _loop_once(): """Run the main loop once This uses the global variables from setup and start, and adds a set of global variables """ global parser, args, config, r, response, patch global monitor, stepsize, scale_rate, offset_rate, scale_shift, offset_shift, scale_ppqn, offset_ppqn, lock, clock, i, clockthread, midithread, redisthread, midiport, previous_midi_play, previous_midi_start, previous_redis_play global start, redis_play, midi_play, midi_start, rate, shift, ppqn, elapsed, naptime redis_play = patch.getint('redis', 'play') midi_play = patch.getint('midi', 'play') midi_start = patch.getint('midi', 'start') if previous_redis_play is None and redis_play is not None: previous_redis_play = not (redis_play) if previous_midi_play is None and midi_play is not None: previous_midi_play = not (midi_play) if previous_midi_start is None and midi_start is not None: previous_midi_start = not (midi_start) # the MIDI port should only be opened once, and only if needed if midi_play and midiport == None: mididevice = patch.getstring('midi', 'device') mididevice = EEGsynth.trimquotes(mididevice) mididevice = process.extractOne( mididevice, mido.get_output_names())[0] # select the closest match try: outputport = mido.open_output(mididevice) monitor.success('Connected to MIDI output') except: raise RuntimeError("cannot connect to MIDI output") # do something whenever the value changes if redis_play and not previous_redis_play: redisthread.setEnabled(True) previous_redis_play = True elif not redis_play and previous_redis_play: redisthread.setEnabled(False) previous_redis_play = False # do something whenever the value changes if midi_play and not previous_midi_play: midithread.setEnabled(True) previous_midi_play = True elif not midi_play and previous_midi_play: midithread.setEnabled(False) previous_midi_play = False # do something whenever the value changes if midi_start and not previous_midi_start: if midiport != None: midiport.send(mido.Message('start')) previous_midi_start = True elif not midi_start and previous_midi_start: if midiport != None: midiport.send(mido.Message('stop')) previous_midi_start = False rate = patch.getfloat('input', 'rate', default=0) rate = EEGsynth.rescale(rate, slope=scale_rate, offset=offset_rate) rate = EEGsynth.limit(rate, 30., 240.) shift = patch.getfloat('input', 'shift', default=0) shift = EEGsynth.rescale(shift, slope=scale_shift, offset=offset_shift) shift = int(shift) ppqn = patch.getfloat('input', 'ppqn', default=0) ppqn = EEGsynth.rescale(ppqn, slope=scale_ppqn, offset=offset_ppqn) ppqn = find_nearest_value([1, 2, 3, 4, 6, 8, 12, 24], ppqn) # show the parameters whose value has changed monitor.update("redis_play", redis_play) monitor.update("midi_play", midi_play) monitor.update("midi_start", midi_start) monitor.update("rate", rate) monitor.update("shift", shift) monitor.update("ppqn", ppqn) # update the clock and redis clockthread.setRate(rate) redisthread.setShift(shift) redisthread.setPpqn(ppqn) # there should not be any local variables in this function, they should all be global if len(locals()): print("LOCALS: " + ", ".join(locals().keys()))
def _start(): '''Start the module This uses the global variables from setup and adds a set of global variables ''' global parser, args, config, r, response, patch, name global debug, mididevice, port, previous_note, UpdateVelocity, UpdateDuration, TriggerThread, trigger_name, trigger_code, code, trigger, this, thread, control_name, control_code, previous_val, SetNoteOff, SetNoteOn, duration_note, lock, midichannel, monitor, monophonic, offset_duration, offset_velocity, outputport, scale_duration, scale_velocity, sendMidi, velocity_note # this can be used to show parameters that have changed monitor = EEGsynth.monitor(name=name, debug=patch.getint('general', 'debug')) # get the options from the configuration file debug = patch.getint('general', 'debug') monophonic = patch.getint('general', 'monophonic', default=1) midichannel = patch.getint( 'midi', 'channel') - 1 # channel 1-16 get mapped to 0-15 mididevice = patch.getstring('midi', 'device') mididevice = EEGsynth.trimquotes(mididevice) mididevice = process.extractOne( mididevice, mido.get_output_names())[0] # select the closest match # values between 0 and 1 work well for the note duration scale_duration = patch.getfloat('scale', 'duration', default=1) offset_duration = patch.getfloat('offset', 'duration', default=0) # values around 64 work well for the note velocity scale_velocity = patch.getfloat('scale', 'velocity', default=1) offset_velocity = patch.getfloat('offset', 'velocity', default=0) # this is only for debugging, and to check which MIDI devices are accessible monitor.info('------ INPUT ------') for port in mido.get_input_names(): monitor.info(port) monitor.info('------ OUTPUT ------') for port in mido.get_output_names(): monitor.info(port) monitor.info('-------------------------') try: outputport = mido.open_output(mididevice) monitor.success('Connected to MIDI output') except: raise RuntimeError("cannot connect to MIDI output") # this is to prevent two messages from being sent at the same time lock = threading.Lock() previous_note = None velocity_note = None duration_note = None def UpdateVelocity(): global velocity_note velocity_note = patch.getfloat('velocity', 'note', default=64) velocity_note = int( EEGsynth.rescale(velocity_note, slope=scale_velocity, offset=offset_velocity)) def UpdateDuration(): global duration_note duration_note = patch.getfloat('duration', 'note', default=None) if duration_note != None: duration_note = EEGsynth.rescale(duration_note, slope=scale_duration, offset=offset_duration) # some minimal time is needed for the duration duration_note = EEGsynth.limit(duration_note, 0.05, float('Inf')) # call them once at the start UpdateVelocity() UpdateDuration() trigger_name = [] trigger_code = [] for code in range(1, 128): trigger_name.append("note%03d" % code) trigger_code.append(code) trigger_name.append("control%03d" % code) trigger_code.append(code) trigger_name.append("polytouch%03d" % code) trigger_code.append(code) for name in [ 'note', 'aftertouch', 'pitchwheel', 'start', 'continue', 'stop', 'reset' ]: trigger_name.append(name) trigger_code.append(None) # each of the Redis messages is mapped onto a different MIDI message trigger = [] for name, code in zip(trigger_name, trigger_code): if config.has_option('trigger', name): # start the background thread that deals with this note this = TriggerThread(patch.getstring('trigger', name), name, code) trigger.append(this) monitor.debug(name, 'trigger configured') # start the thread for each of the triggers for thread in trigger: thread.start() control_name = [] control_code = [] for code in range(1, 128): control_name.append("note%03d" % code) control_code.append(code) control_name.append("control%03d" % code) control_code.append(code) control_name.append("polytouch%03d" % code) control_code.append(code) for name in [ 'note', 'aftertouch', 'pitchwheel', 'start', 'continue', 'stop', 'reset' ]: control_name.append(name) control_code.append(None) # control values are only interesting when different from the previous value previous_val = {} for name in control_name: previous_val[name] = None # there should not be any local variables in this function, they should all be global if len(locals()): print('LOCALS: ' + ', '.join(locals().keys()))
def get_midi_out_list(): return mido.get_output_names()
#!/usr/bin/env python """ List available PortMidi ports. """ from __future__ import print_function import sys import mido def print_ports(heading, port_names): print(heading) for name in port_names: print(" '{}'".format(name)) print() print() print_ports('Input Ports:', mido.get_input_names()) print_ports('Output Ports:', mido.get_output_names())
def get_midioutputs(self): # helper function for the gui app return mido.get_output_names()
def __init__(self, input_midi_ports, output_midi_ports, texture_type, passthrough=True, playback_offset=0.0): self._texture_type = texture_type self._passthrough = passthrough self._playback_offset = playback_offset # When `passthrough` is True, this is the set of open MIDI note # pitches. self._open_notes = set() # This lock is used by the serialized decorator. self._lock = threading.RLock() # A dictionary mapping a compiled MidiSignal regex to a condition variable # that will be notified when a matching messsage is received. self._signals = {} # A dictionary mapping a compiled MidiSignal regex to a list of functions # that will be called with the triggering message in individual threads when # a matching message is received. self._callbacks = defaultdict(list) # A dictionary mapping integer control numbers to most recently-received # integer value. self._control_values = {} # Threads actively being used to capture incoming messages. self._captors = [] # Potentially active player threads. self._players = [] self._metronome = None # Open MIDI ports. if input_midi_ports: for port in input_midi_ports: if isinstance(port, ports.BaseInput): inport = port else: virtual = port not in get_input_names() if virtual: logging.info( "Opening '%s' as a virtual MIDI port for input.", port) inport = open_input(port, virtual=virtual) # Start processing incoming messages. inport.callback = self._timestamp_and_handle_message # this is needed because otherwise inport will get # garbage collected and stop receiving input events self._inport = inport else: logging.warning('No input port specified. Capture disabled.') self._inport = None outports = [] for port in output_midi_ports: if isinstance(port, ports.BaseInput): outports.append(port) else: virtual = port not in get_output_names() if virtual: logging.info( "Opening '%s' as a virtual MIDI port for output.", port) outports.append(open_output(port, virtual=virtual)) self._outport = ports.MultiPort(outports)
import numpy as np from .audio import load_audio_file from .midi import load_midi, write_midi from ..utils import suppress_warnings, string_types ENCODING = 'utf8' # dtype for numpy structured arrays that contain labelled segments # 'label' needs to be castable to str SEGMENT_DTYPE = [('start', np.float), ('end', np.float), ('label', object)] # SETUP MIDI IO, just pick the first port, what could go wrong? import mido import re midi_ports = mido.get_output_names() midi_port = midi_ports[0] for port in midi_ports: if re.match('IAC', port) or re.match('LoopBe', port): midi_port = port outport = mido.open_output(midi_port) midi_ports = mido.get_input_names() for port in midi_ports: if re.match('IAC', port) or re.match('LoopBe', port): midi_port = port inport = mido.open_input(midi_port) MIDI_CHANNEL = 11 MIDI_NOTE = 36
import mido mido.get_input_names() mido.get_output_names() port2 = mido.open_output('loopMIDI Port 2 3') channel = 2 channel_max = 3 try: with mido.open_input('loopMIDI Port 0') as inport: while True: for msg in inport: print(msg) #print(dir(msg)) if msg.type == 'control_change' and msg.control == 1: channel += 1 # channel = 0 if channel > channel_max: channel = 2 else: msg_copy = msg msg_copy.channel = channel # output = mido.Message(msg.type, note=msg.note, velocity=msg.velocity, channel=2) port2.send(msg_copy) print(msg_copy) print('sent on channel {}'.format(channel)) except: pass
def generate(unused_argv): # Downloads the bundle from the magenta website mm.notebook_utils.download_bundle("drum_kit_rnn.mag", "bundles") bundle = mm.sequence_generator_bundle.read_bundle_file( os.path.join("bundles", "drum_kit_rnn.mag")) # Initialize the generator "drum_kit" generator_map = drums_rnn_sequence_generator.get_generator_map() generator = generator_map["drum_kit"](checkpoint=None, bundle=bundle) generator.initialize() # Define constants qpm = 120 num_bars = 3 seconds_per_step = 60.0 / qpm / generator.steps_per_quarter num_steps_per_bar = constants.DEFAULT_STEPS_PER_BAR seconds_per_bar = num_steps_per_bar * seconds_per_step # Use a priming sequence primer_sequence = mm.midi_io.midi_file_to_note_sequence( os.path.join("primers", "Jazz_Drum_Basic_1_bar.mid")) primer_start_time = 0 primer_end_time = primer_start_time + seconds_per_bar # Calculates the generation start and end time generation_start_time = primer_end_time generation_end_time = generation_start_time + (seconds_per_bar * num_bars) generator_options = generator_pb2.GeneratorOptions() generator_options.args['temperature'].float_value = 1.1 generator_options.generate_sections.add(start_time=generation_start_time, end_time=generation_end_time) # Generates on primer sequence sequence = generator.generate(primer_sequence, generator_options) # Outputs the plot os.makedirs("output", exist_ok=True) plot_file = os.path.join("output", "out.html") pretty_midi = mm.midi_io.note_sequence_to_pretty_midi(sequence) plotter = Plotter(live_reload=True) plotter.show(pretty_midi, plot_file) print(f"Generated plot file: {os.path.abspath(plot_file)}") # We find the proper input port for the software synth # (which is the output port for Magenta) output_ports = [ name for name in mido.get_output_names() if args.midi_port in name ] if not output_ports: raise Exception(f"Cannot find proper output ports in: " f"{mido.get_output_names()}") print(f"Playing generated MIDI in output port names: {output_ports}") # Start a new MIDI hub on that port (output only) midi_hub = MidiHub(input_midi_ports=[], output_midi_ports=output_ports, texture_type=None) # Start on a empty sequence, allowing the update of the # sequence for later. empty_sequence = music_pb2.NoteSequence() player = midi_hub.start_playback(empty_sequence, allow_updates=True) player._channel = 9 # We want a period in seconds of 4 bars period = Decimal(240) / qpm period = period * (num_bars + 1) sleeper = concurrency.Sleeper() index = 0 while True: try: # We get the next tick time by using the period # to find the absolute tick number. now = Decimal(time.time()) tick_number = int(now // period) tick_number_next = tick_number + 1 tick_time = tick_number * period tick_time_next = tick_number_next * period # Update the player time to the current tick time sequence_adjusted = music_pb2.NoteSequence() sequence_adjusted.CopyFrom(sequence) sequence_adjusted = adjust_sequence_times(sequence_adjusted, float(tick_time)) player.update_sequence(sequence_adjusted, start_time=float(tick_time)) # Generate a new sequence based on the previous sequence index = index + 1 generator_options = generator_pb2.GeneratorOptions() generator_options.args['temperature'].float_value = 1 generation_start_time = index * period generation_end_time = generation_start_time + period generator_options.generate_sections.add( start_time=generation_start_time, end_time=generation_end_time) sequence = generator.generate(sequence, generator_options) sequence = trim_note_sequence(sequence, generation_start_time, generation_end_time) # Sleep until the next tick time sleeper.sleep_until(float(tick_time_next)) except KeyboardInterrupt: print(f"Stopping") return 0
print("Error: cannot connect to redis server") exit() # combine the patching from the configuration file and Redis patch = EEGsynth.patch(config, r) del config # this determines how much debugging information gets printed debug = patch.getint('general', 'debug') # this is only for debugging, and check which MIDI devices are accessible print('------ INPUT ------') for port in mido.get_input_names(): print(port) print('------ OUTPUT ------') for port in mido.get_output_names(): print(port) print('-------------------------') # on windows the input and output are different, on unix they are the same # use "input/output" when specified, or otherwise use "device" for both try: mididevice_input = patch.getstring('midi', 'input') except: mididevice_input = patch.getstring('midi', 'device') # fallback try: mididevice_output = patch.getstring('midi', 'output') except: mididevice_output = patch.getstring('midi', 'device') # fallback print(mididevice_input)
def __init__(self): self.out = mido.open_output(mido.get_output_names()[-1]) self.channels = [] self.tempo = INITIAL_TEMPO
def findMidiCable(midiCableName): names = mido.get_output_names() for name in names: if name.startswith(midiCableName): return True, name return False, midiCableName
# pip install python-rtmidi # pip install mido import rtmidi import mido import time print("Midi output ports: ", mido.get_output_names()) # midiOutput = mido.open_output("LoopBe Internal MIDI 1") # midiOutput = mido.open_output("IAC Driver Bus 1") def sendNoteOn(note, velocity): message = mido.Message('note_on', note=note, velocity=velocity) midiOutput.send(message) def sendNoteOff(note, velocity): message = mido.Message('note_off', note=note, velocity=velocity) midiOutput.send(message) def sendControlChange(control, value): message = mido.Message('control_change', control=control, value=value) midiOutput.send(message) # for value in range(8): # sendNoteOn(60+value, 100) # time.sleep(0.5) # sendNoteOff(60+value, 0)
def list_output_devices(): return mido.get_output_names()
import mido print(mido.get_output_names()) print(mido.get_input_names()) toFL = mido.open_output(name='loopMIDI Port 10', virtual=False) fromFL = mido.open_input(name='loopMIDI Port 1 10') while (1): msg = fromFL.poll() if (msg): print(msg)
'was held! adding note_queue to chord_progression.' ) chord_progression.insert(0, note_queue) note_queue = [] return print('computer should not record.') computer_should_record = False time_since_pedal_released = time.time() else: pass input_name = mido.get_input_names()[0] input_port = mido.open_input(input_name, callback=handle_message) output_name = mido.get_output_names()[0] output_port = mido.open_output(output_name) def main(): global note_queue global input_port global output_port global computer_should_record global init_time global last_time while not init: time.sleep(0.1) init_time = time.time()
def listen(self): for name in mido.get_output_names(): t = threading.Thread(target=self._listen, args=(name, )) t.daemon = True t.start()
import mido import sys import time midi_name = None for name in mido.get_output_names(): if name.startswith("VYPYR"): midi_name = name if not midi_name: print("Could not find VYPYR interface") sys.exit(1) output = mido.open_output(midi_name) while True: for program in range(0, 4): msg = mido.Message("program_change", program=program) output.send(msg) print(program) time.sleep(1)
if "-i" in argv: [ins, outs] = p.listDevices() print "[+] List of input devices" for i in range(len(ins)): print "%d: %s" % (i + 1, ins[i]) inDev = ins[int(raw_input("Select input device: ")) - 1] else: inDev = mido.get_input_names()[0] if "-o" in argv: print "[+] List of output devices" for i in range(len(ins)): print "%d: %s" % (i + 1, outs[i]) outDev = ins[int(raw_input("Select output device: ")) - 1] else: outDev = mido.get_output_names()[0] ### Connecting to input and output devices print "Testing inDev and outDev" if p.connect(inDev, outDev): if verbose: print "PASSED" else: if verbose: print "FAILED" ### Connecting recorder with piano print "Testing recorder and piano connection" if rec.setPiano(p): if rec.piano == p and rec.handler == p.input.callback: if verbose:
print("Error: cannot connect to redis server") exit() # combine the patching from the configuration file and Redis patch = EEGsynth.patch(config, r) del config # this determines how much debugging information gets printed debug = patch.getint('general', 'debug') # this is only for debugging print('------ INPUT ------') for port in mido.get_input_names(): print(port) print('------ OUTPUT ------') for port in mido.get_output_names(): print(port) print('-------------------------') mididevice = patch.getstring('midi', 'device') try: inputport = mido.open_input(mididevice) if debug > 0: print("Connected to MIDI input") except: print("Error: cannot connect to MIDI input") exit() try: outputport = mido.open_output(mididevice) if debug > 0:
def __init__(self, options): self.midi_inport = None if options.settings['inport'] == 'default': # Get first inputname available_ports = mido.get_output_names() if available_ports: self.midi_inport = available_ports[0] else: print("No input name passed in, none found, turning midi off") self.midi_inport = None else: self.midi_inport = options.settings['inport'] self.sysex_prefix = [] for manf_byte in options.settings['sysexmanf'].split(' '): self.sysex_prefix.append(int(manf_byte, 0)) for channel in options.settings['inchannel'].split(' '): self.sysex_prefix.append(int(channel, 0) - 1) self.channel = int(options.settings['inchannel']) - 1 try: self.bcontrolnum = int(options.settings['bcontrolnum'], 0) except ValueError: self.bcontrolnum = -1 try: self.tcontrolnum = int(options.settings['tcontrolnum'], 0) except ValueError: self.tcontrolnum = -1 try: self.rcontrolnum = int(options.settings['rcontrolnum'], 0) except ValueError: self.rcontrolnum = -1 try: self.pcontrolnum = int(options.settings['pcontrolnum'], 0) except ValueError: self.pcontrolnum = -1 try: self.bsysexnum = int(options.settings['bsysexnum'], 0) except ValueError: self.bsysexnum = -1 try: self.tsysexnum = int(options.settings['tsysexnum'], 0) except ValueError: self.tsysexnum = -1 try: self.rsysexnum = int(options.settings['rsysexnum'], 0) except ValueError: self.rsysexnum = -1 try: self.fsysexnum = int(options.settings['fsysexnum'], 0) except ValueError: self.fsysexnum = -1 try: self.psysexnum = int(options.settings['psysexnum'], 0) except ValueError: self.psysexnum = -1 self.bpm = BPM() self.beat = Beat() self.rms = RMS() self.frequencies = Frequencies() self.pitch = Pitch()
# combine the patching from the configuration file and Redis patch = EEGsynth.patch(config, r) # this can be used to show parameters that have changed monitor = EEGsynth.monitor() # get the options from the configuration file debug = patch.getint('general', 'debug') monophonic = patch.getint('general', 'monophonic', default=1) midichannel = patch.getint('midi', 'channel') - 1 # channel 1-16 get mapped to 0-15 mididevice = patch.getstring('midi', 'device') mididevice = EEGsynth.trimquotes(mididevice) mididevice = process.extractOne( mididevice, mido.get_output_names())[0] # select the closest match # values between 0 and 1 work well for the note duration scale_duration = patch.getfloat('scale', 'duration', default=1) offset_duration = patch.getfloat('offset', 'duration', default=0) # values around 64 work well for the note velocity scale_velocity = patch.getfloat('scale', 'velocity', default=1) offset_velocity = patch.getfloat('offset', 'velocity', default=0) # this is only for debugging, and to check which MIDI devices are accessible print('------ INPUT ------') for port in mido.get_input_names(): print(port) print('------ OUTPUT ------') for port in mido.get_output_names(): print(port)
import mido from string import ascii_lowercase print('starting up launchpad controls') print(mido.get_output_names()) portmidi = mido.Backend('mido.backends.portmidi') output = portmidi.open_output('Launchpad S MIDI 1') colors = { 'off': 0, 'red.low': 1, 'red.medium': 2, 'red.high': 3, 'yellow.low': 17, 'yellow.medium': 34, 'yellow.high': 54, 'orange.low': 45, 'orange.medium': 46, 'orange.high': 23, 'green.low': 16, 'green.medium': 32, 'green.high': 48 } def setlight(where, what): if not 'coordinate' in where: # ignore if it is not on the board return coord = where['coordinate']
def __init__(self): soundfonts = sorted(glob.glob("soundfonts/?.sf2")) # Pre-flight check if not soundfonts: print("No soundfont could be found. Fluidsynth cannot start.") print("Suggestion: 'cd soundfonts; ./download-soundfonts.sh'") exit(1) # Try to detect which sound driver to use. audio_driver = os.environ.get("GRIODE_AUDIO_DRIVER") if audio_driver is None: uid = os.getuid() pulseaudio_pidfile = "/run/user/{}/pulse/pid".format(uid) if os.path.isfile(pulseaudio_pidfile): try: pulseaudio_pid = int(open(pulseaudio_pidfile).read()) except: logging.exception("Could not read pulseaudio PID") pulseaudio_pid = None if pulseaudio_pid is not None: if os.path.isdir("/proc/{}".format(pulseaudio_pid)): audio_driver = "pulseaudio" if audio_driver is None: if sys.platform == "linux": audio_driver = "alsa" if sys.platform == "darwin": audio_driver = "coreaudio" if audio_driver is None: logging.error("Could not determine audio driver.") logging.error("Please set GRIODE_AUDIO_DRIVER.") exit(1) logging.info("Using audio driver: {}".format(audio_driver)) popen_args = [ "fluidsynth", "-a", audio_driver, "-o", "synth.midi-bank-select=mma", "-o", "synth.sample-rate=44100", "-c", "8", "-p", "griode" ] # Invoke fluidsynth a first time to enumerate instruments logging.debug("Invoking fluidsynth to enumerate instruments...") self.fluidsynth = subprocess.Popen(popen_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) msg = "" for i, soundfont in enumerate(soundfonts): font_id = i + 1 offset = i * 1000 msg += "load {} 1 {}\n".format(soundfont, offset) msg += "inst {}\n".format(font_id) self.fluidsynth.stdin.write(msg.encode("ascii")) self.fluidsynth.stdin.flush() self.fluidsynth.stdin.close() output = self.fluidsynth.stdout.read().decode("ascii") instruments = re.findall("\n([0-9]{3,})-([0-9]{3}) (.*)", output) self.instruments = [] for bank, prog, name in instruments: bank = int(bank) prog = int(prog) font_id = bank // 1000 instrument = Instrument(font_id, prog, bank, name) self.instruments.append(instrument) logging.info("Found {} instruments".format(len(self.instruments))) self.fonts = build_fonts(self.instruments) # Re-order the instruments list # (This is used to cycle through instruments in order) def get_instrument_order(i): return (i.font_index, i.program, i.bank_index) self.instruments.sort(key=get_instrument_order) # And now, restart fluidsynth but for actual synth use logging.debug("Starting fluidsynth as a synthesizer...") self.fluidsynth = subprocess.Popen(popen_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.fluidsynth.stdin.write(msg.encode("ascii")) self.fluidsynth.stdin.flush() # Find the MIDI port created by fluidsynth and open it logging.debug("Waiting for fluidsynth MIDI port to show up...") deadline = time.time() + 5 while time.time() < deadline: port_names = [p for p in mido.get_output_names() if "griode" in p] if port_names == []: time.sleep(0.1) continue if len(port_names) > 1: logging.warning("Found more than one port for griode") self.synth_port = mido.open_output(port_names[0]) logging.info("Connected to MIDI output {}".format(port_names[0])) break else: logging.error("Failed to locate the fluidsynth port!") exit(1)
def __init__(self, master, config): # Sets up main window and global config. self.window = master self.config = config master.title("Cooltrollers") #master.iconbitmap(default="controller.ico") # Adds menus. menuBar = Menu(master) fileMenu = Menu(menuBar, tearoff=0) optionsMenu = Menu(menuBar, tearoff=0) menuBar.add_cascade(label="File", menu=fileMenu) fileMenu.add_command(label="Controller", command=lambda: Controller(self.outport, config)) fileMenu.add_command(label="Exit", command=quit) menuBar.add_cascade(label="Options", menu=optionsMenu) optionsMenu.add_command(label="Button Manager", command=self.buttonManager) optionsMenu.add_command(label="Controller Manager", command=self.controllerManager) master.config(menu=menuBar) master.resizable(0, 0) # Initializes mido, the MIDI outport, and global variables that are used in functionality(). midi_out = mido.get_output_names() self.octave = 0 self.counter = -1 # Sets up octave display. Every time it's changed via + or -, the display updates accordingly (via statements in functionality()) self.currentOctaveText = StringVar() self.currentOctaveText.set("Current octave: {0}".format( int((self.octave / 12) + 4))) octaveDisplay = Label(master, textvariable=self.currentOctaveText, anchor=NE) octaveDisplay.grid(row=0, columnspan=2) # Any key that's pressed activates functionality(), which plays notes. master.bind("<Key>", self.functionality) # Combo box and apply button for selecting MIDI port. self.port = StringVar(master) self.port.set(midi_out[0]) self.currentPort = self.port portSelect = OptionMenu(master, self.port, *midi_out) portSelect.grid(row=1) applyPortButton = Button(master, text="Apply", command=self.applyPort) applyPortButton.grid(row=1, column=1) self.outport = mido.open_output(self.currentPort.get()) # Setting up proper binding settings for playback. # This right here is all the General MIDI instruments in one list. self.instruList = [ '1 Acoustic Grand Piano', '2 Bright Acoustic Piano', '3 Electric Grand Piano', '4 Honky-tonk Piano', '5 Electric Piano 1', '6 Electric Piano 2', '7 Harpsichord', '8 Clavinet', '9 Celesta', '10 Glockenspiel', '11 Music Box', '12 Vibraphone', '13 Marimba', '14 Xylophone', '15 Tubular Bells', '16 Dulcimer', '17 Drawbar Organ', '18 Percussive Organ', '19 Rock Organ', '20 Church Organ', '21 Reed Organ', '22 Accordion', '23 Harmonica', '24 Tango Accordion', '25 Acoustic Guitar (nylon)', '26 Acoustic Guitar (steel)', '27 Electric Guitar (jazz)', '28 Electric Guitar (clean)', '29 Electric Guitar (muted)', '30 Overdriven Guitar', '31 Distortion Guitar', '32 Guitar harmonics', '33 Acoustic Bass', '34 Electric Bass (finger)', '35 Electric Bass (pick)', '36 Fretless Bass', '37 Slap Bass 1', '38 SlapBass 2', '39 Synth Bass 1', '40 Synth Bass 2', '41 Violin', '42 Viola', '43 Cello', '44 Contrabass', '45 Tremolo Strings', '46 Pizzicato Strings', '47 Orchestral Harp', '48 Timpani', '49 String Ensemble 1', '50 String Ensemble 2', '51 Synth Strings 1', '52 Synth Strings 2', '53 Choir Aahs', '54 Voice Oohs', '55 Synth Voice', '56 Orchestra Hit', '57 Trumpet', '58 Trombone', '59 Tuba', '60 Muted Trumpet', '61 French Horn', '62 Brass Section', '63 Synth Brass 1', '64 Synth Brass 2', '65 Soprano Sax', '66 Alto Sax', '67 Tenor Sax', '68 Baritone Sax', '69 Oboe', '70 English Horn', '71 Bassoon', '72 Clarinet', '73 Piccolo', '74 Flute', '75 Recorder', '76 Pan Flute', '77 Blown Bottle', '78 Shakuhachi', '79 Whistle', '80 Ocarina', '81 Lead 1 (square)', '82 Lead 2 (sawtooth)', '83 Lead 3 (calliope)', '84 Lead 4 (chiff)', '85 Lead 5 (charang)', '86 Lead 6 (voice)', '87 Lead 7 (fifths)', '88 Lead 8 (bass + lead)', '89 Pad 1 (new age)', '90 Pad 2 (warm)', '91 Pad 3 (polysynth)', '92 Pad 4 (choir)', '93 Pad 5 (bowed)', '94 Pad 6 (metallic)', '95 Pad 7 (halo)', '96 Pad 8 (sweep)', '97 FX 1 (rain)', '98 FX 2 (soundtrack)', '99 FX 3 (crystal)', '100 FX 4 (atmosphere)', '101 FX 5 (brightness)', '102 FX 6 (goblins)', '103 FX 7 (echoes)', '104 FX 8 (sci-fi)', '105 Sitar', '106 Banjo', '107 Shamisen', '108 Koto', '109 Kalimba', '110 Bag pipe', '111 Fiddle', '112 Shanai', '113 Tinkle Bell', '114 Agogo', '115 Steel Drums', '116 Woodblock', '117 Taiko Drum', '118 Melodic Tom', '119 Synth Drum', '120 Reverse Cymbal', '121 Guitar Fret Noise', '122 Breath Noise', '123 Seashore', '124 Bird Tweet', '125 Telephone Ring', '126 Helicopter', '127 Applause', '128 Gunshot' ] # Checks whether there's a settings file. Otherwise, the user must set up button binds in the bind manager. if (os.path.isfile('settings.ini')): self.config.read('settings.ini') keyString = self.config.get('Button Binds', 'Keys') instrumentString = self.config.get('Button Binds', 'Instruments') noteString = self.config.get('Button Binds', 'Notes') self.key = keyString.split(",") self.instruString = instrumentString.split(",") self.note = noteString.split(",") buttonString = self.config.get('Joystick Binds', 'Buttons') btnInstrumentString = self.config.get('Joystick Binds', 'Instruments') btnNoteString = self.config.get('Joystick Binds', 'Notes') self.button = buttonString.split(",") self.btnInstruString = btnInstrumentString.split(",") self.btnNote = btnNoteString.split(",") for x in range(16): self.button[x] = int(self.button[x]) with open('settings.ini', 'w') as configfile: self.config.write(configfile) # Config file initial setup. Uses strings with commas separating list items to store in the file. else: self.clearBinds() # Getting the number of the instrument for passing to mido. for x in range(16): if (self.instruString[x][1] == ' '): self.instruNum = int(self.instruString[x][0]) elif (self.instruString[x][2] == ' '): self.instruNum = int(self.instruString[x][:2]) else: self.instruNum = int(self.instruString[x][:3]) self.outport.send( mido.Message('program_change', channel=x, program=self.instruNum - 1))
def getAllMidiOutputs(self): try: return mido.get_output_names() except Exception as e: print("Impossible to run mido_get_output_names", e) return []
args = parser.parse_args() if args.version: print("Llia version %s.%s.%s" % constants.VERSION) sys.exit(0) if args.usage: print(USAGE) sys.exit(0) if args.midi_ports: import mido print("\nAvailable MIDI input ports:") for p in mido.get_input_names(): print("\t%s" % p) print("\nAvailable MIDI output ports:") for p in mido.get_output_names(): print("\t%s" % p) print() sys.exit(0) if args.listgui: print("\nAvailable GUI options:") for g in constants.GUI_OPTIONS: print("\t%-12s%s" % g) print() sys.exit(0) config = LliaConfig.create_instance(args) import llia.manifest