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 play_from_encoder(directory):
    encoder = pickle_loader(directory + ".pkl")
    sample_rate = encoder.sample_rate
    buffer_size = 10 # sample buffer for playback. Hevent really determined what i does qualitatively. Probably affects latency
    play_duration = 100 # play duration in miliseconds
    pygame.mixer.pre_init(sample_rate, -16, 2,buffer = buffer_size) # 44.1kHz, 16-bit signed, stereo
    pygame.init()
    volLeft = 0.5;volRight=0.5 # Volume
    z_val = np.zeros([1,encoder.dimZ]) # Initial latent variable values
    port = mido.open_input(mido.get_input_names()[0]) # midi port. chooses the first midi device it detects.
    while True:
        mu_out = encoder.generateOutput(z_val)
        for msg in port.iter_pending():
            if msg.channel < z_val.shape[1]:
                z_val[0,msg.channel] = msg.value
            else:
                print "Midi channel beyond latent variables"
        mu_out = map_to_range_symmetric(mu_out,[-1,1],[-32768,32768])
        mu_out = mu_out.astype(np.int16)
        mu_out = np.array(zip(mu_out,mu_out)) # make stereo channel with same output
        sound = pygame.sndarray.make_sound(mu_out)
        channel = sound.play(-1)
        channel.set_volume(volLeft,volRight)
        pygame.time.delay(play_duration)
        sound.stop()
示例#3
0
 def open_port(self, portName):
     if not self.port or self.port.name != portName:
         if self.port:
             self.port.close()
         print(portName)
         if portName in mido.get_input_names():
             self.port = mido.open_input(portName, callback=self.dispatch_midi)
示例#4
0
def main():
    output_name = ''
    input_name = ''
    device_names = mido.get_input_names()
    for device_name in device_names:
        # FIXME: Heuristic to get our USB stick device
        if '-' in device_name and 'Through' not in device_name:
            output_name = device_name
            break
    else:
        print "No appropriate MIDI device. MIDI device names: ", device_names
        return

    print "Connected devices: ", device_names
    print "Opening device: ", output_name

    # or, with mido.open_ioport(output_name) as iop:
    with mido.open_output(output_name) as output:
        with mido.open_input(output_name, callback=print_message) as inp:
            #msg = mido.Message('sysex', data=[10]) Set type to digital output
            #msg = mido.Message('sysex', data=[101]) # send watchdog timer reset
            #msg = mido.Message('sysex', data=[99]) # Request device type
            msg = mido.Message('sysex', data=[77]) # Request device name
            #msg = mido.Message('sysex', data=[54,1,2,3,4]) # Set device name to '0x010203'
            #msg = mido.Message('note_on')
            print "sending msg: ", msg
            output.send(msg);
            print "waiting for response message"
            time.sleep(1) # Pause while we get MIDO callback print-outs
    print "script done"
示例#5
0
    def messages(self):
        if not mido:
            raise ValueError(MIDO_ERROR)
        try:
            input_names = mido.get_input_names()
        except AttributeError as e:
            e.args = (MIDO_ERROR,) + e.args
            raise

        ports = [mido.open_input(i) for i in input_names]

        if not ports:
            log.error('control.midi: no MIDI ports found')
            return

        port_names = ', '.join('"%s"' % p.name for p in ports)
        log.info('Starting to listen for MIDI on port%s %s',
                 '' if len(ports) == 1 else 's', port_names)
        for port, msg in mido.ports.MultiPort(ports, yield_ports=True):
            mdict = dict(vars(msg), port=port)

            if self.use_note_off:
                if msg.type == 'note_on' and not msg.velocity:
                    mdict.update(type='note_off')
            elif self.use_note_off is False:
                if msg.type == 'note_off':
                    mdict.update(type='note_on', velocity=0)

            yield mdict
示例#6
0
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!")
示例#7
0
 def __init__(self):
     self.log = logger()
     if 'Teensy MIDI' not in mido.get_input_names():
         self.log.error('Error connecting to Teensy foot controller.')
         sys.exit(1)
     self.input = mido.open_input(MidiController.DEVICE)
     self.log.info('Device Registered.')
示例#8
0
    def start_key_thread(self):
        port_name = mido.get_input_names()[0]
        with mido.open_input(port_name) as inport:
            for msg in inport:

                if self.done: return
                if not self.current_note_to_play:
                    print("cannot play notes during this state!")
                    continue

                if hasattr(msg, 'note') and hasattr(msg, 'velocity') and msg.velocity > 0:
                    print(msg.note)
                    self.total_notes += 1
                    self.display_total_notes = self.info_font.render("Total Notes: " + str(self.total_notes), True,
                                                                     (205, 92, 92))
                if hasattr(msg, 'note') and msg.note % 12 == self.current_note_to_play % 12 and hasattr(msg,
                                                                                                        'velocity') and msg.velocity > 0:
                    self.notes_correct += 1
                    self.display_note = self.note_font.render("Correct!!!", True, (0, 128, 0))
                    self.display_notes_correct = self.info_font.render("Correct Notes: " + str(self.notes_correct),
                                                                       True, (205, 92, 92))
                    self.display_average_tries = self.info_font.render(
                        "Average Tries: " + str(round(self.total_notes / self.notes_correct)), True, (205, 92, 92))

                    self.average_note_time += time.time() - self.note_start_time
                    self.display_average_time = self.info_font.render(
                        "Average Time: " + str(round(self.average_note_time / self.notes_correct, 1)) + " seconds",
                        True,
                        (205, 92, 92))
                    self.current_note_to_play = 0
                    Thread(target=self.new_note()).start()
示例#9
0
def main():
    """reads the config file first, then opens the midi input and waits for commands"""
    device, midi_to_shortcut = read_conf()

    print(mido.get_input_names())
    # input the name off your Midi device here.
    with mido.open_input(device) as inp:
        for message in inp:
            process_message(message, midi_to_shortcut)
示例#10
0
文件: mt2.py 项目: fwilson42/mt2
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()
示例#11
0
 def __init__(self, ac):
     """Register the midi device.
     :param ac: The audio controller object
     """
     self.log = logger()
     if 'Teensy MIDI' not in mido.get_input_names():
         self.log.error('Error connecting to Teensy foot controller.')
         sys.exit(1)
     self.input = mido.open_input(MidiController.DEVICE)
     self.log.info('Device Registered.')
     self.ac = ac
示例#12
0
def open_midi_input_port(regex):
    """Open a MIDI input port matching a given regular expression, and return it.
    """
    inports = mido.get_input_names()
    for name in inports:
        if re.match(regex, name):
            try:
                p = mido.open_input(name)
            except:
                pass
            else:
                return p
示例#13
0
	def _open_input(self, port):
		if self._in_port is None:
			try:
				self._in_port = mido.open_input(port)
			except IOError:
				print "Couldn't open input port '%s'. The following MIDI ports are available:" % port
				for p in mido.get_input_names():
					print "'%s'" % p
				raise
		else:
			assert self._in_port.name == port
		return self._in_port
示例#14
0
 def log_listener():
     try:
         device_names = mido.get_input_names()
         devices = [ mido.open_input(device_name) for device_name in device_names ]
         devices = mido.ports.MultiPort(devices)
         for msg in devices:
             if hasattr(ns, 'midi_log_active'):
                 dsp.log(msg)
             else:
                 continue
     except IOError:
         dsp.log('Could not open MIDI devices for logging %s' % str(device_names))
 def start(self):
     while True:
         names = mido.get_input_names()
         print names
         for id in IGNORED_DEVICES:
             names.remove(id) 
         (newDevices_l, deletedDevices_l) = self.getDeviceDiff(names)
         print newDevices_l, deletedDevices_l, self.devices_d.keys()
         for newDeviceName in newDevices_l:
             self.addDevice(newDeviceName)
         for deletedDeviceName in deletedDevices_l:
             self.deleteDevice(deletedDeviceName)
         time.sleep(1)
示例#16
0
文件: midi.py 项目: nanotone/midihub
 def __init__(self, emit):
     self.emit = emit
     port_names = mido.get_input_names()
     if not port_names:
         raise IndexError("No MIDI input ports found")
     if len(port_names) == 1:
         idx = 0
         logging.info("Choosing MIDI input port %s", port_names[0])
     else:
         print("MIDI input ports:")
         for (idx, name) in enumerate(port_names):
             print("{}. {}".format(idx, name))
         idx = int(raw_input("Which MIDI input port? "))
         assert 0 <= idx < len(port_names)
     self.midi_in = mido.open_input(port_names[idx])
示例#17
0
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 build_ui(self):

        self.confirm_button = QtGui.QPushButton("Confirm")

        self.confirm_button.clicked.connect(self.close)

        if self.model.get_selected_input() == 'Midi Source':

            self.in_port_label = QtGui.QLabel("Available Input Ports")

            self.available_ports = mido.get_input_names()

            self.available_ports.insert(0, '')

            selected_in_port = self.model.get_selected_in_port()

            self.in_ports_combo_box = QtGui.QComboBox()

            for port in self.available_ports:

                self.in_ports_combo_box.addItem(port)

            if selected_in_port in self.available_ports:

                "Get the index of that item"
                index = self.available_ports.index(selected_in_port)

                self.in_ports_combo_box.setCurrentIndex(index)
            else:

                self.in_ports_combo_box.setCurrentIndex(0)

            self.grid = QtGui.QGridLayout()

            self.grid.addWidget(self.in_port_label, 0, 0)

            self.grid.addWidget(self.in_ports_combo_box, 0, 1)

            self.grid.addWidget(self.confirm_button, 1, 1)

        else:

            self.build_no_settings_ui()

        self.setLayout(self.grid)
示例#19
0
    def start_key_thread(self):
        port_name = mido.get_input_names()[0]
        with mido.open_input(port_name) as inport:
            for msg in inport:

                if self.done: return

                if hasattr(msg, 'note') and hasattr(msg, 'velocity') and msg.velocity > 0:
                    print(msg.note)
                    self.total_notes_played += 1
                    self.display_total_notes_played = self.info_font.render(
                        "Total Notes Played: " + str(self.total_notes_played), True,
                        (205, 92, 92))
                if hasattr(msg, 'note') and msg.note % 12 == self.current_note_to_play % 12 and hasattr(msg,
                                                                                                        'velocity') and msg.velocity > 0:
                    self.update_display_note(False)
                    self.notes_correct += 1
                    self.display_notes_correct = self.info_font.render("Correct Notes: " + str(self.notes_correct), True,
                                                           (205, 92, 92))
示例#20
0
    def __init__(self, target=MIDIOUT_DEFAULT):
        self.midi = None
        # don't ignore MIDI clock messages (is on by default)
        # TODO: check
        # self.midi.ignore_types(timing=False)
        self.clocktarget = None

        ports = mido.get_input_names()
        if len(ports) == 0:
            raise Exception("No MIDI output ports found")

        for name in ports:
            if name == target:
                isobar.log("Found MIDI input (%s)", name)
                self.midi = mido.open_input(name, callback=self.callback)

        if self.midi is None:
            isobar.log("Could not find MIDI source %s, using default", target)
            self.midi = mido.open_input(callback=self.callback)
示例#21
0
文件: splash.py 项目: kaos/Llia
 def select_midi_input_port(self):
     acc = []
     for p in mido.get_input_names():
         acc.append(p)
     while True:
         print()
         mrn = self.config["midi-receiver-name"]
         for n, p in enumerate(acc):
             print("    [%d] %s" % (n+1, p))
         print("\nPress [Enter] to select default")
         usr = infn("Select MIDI input port (%s) > " % mrn)
         if not usr: break
         try:
             n = int(usr)
             if 0 < n <= len(acc):
                 mrn = acc[n-1]
                 self.config["midi-receiver-name"] = mrn
                 break
             else:
                 raise ValueError()
         except ValueError:
             print("ERROR")
示例#22
0
 def get_port():  # informs user of available ports and returns their choice
     port_list = mido.get_input_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('\n Choose port by number: '))]
示例#23
0
 def get_midiinputs(self):
     # helper function for the gui app
     return mido.get_input_names()
示例#24
0
import mido
from pprint import pprint

midi_devices = mido.get_input_names()
port_dict = {}

while True:
    pprint([(i, midi_devices[i]) for i in range(len(midi_devices))])
    user_input = raw_input('select midi device number: ')
    print(midi_devices)
    if user_input is "" or midi_devices is []:
        break
    try:
        which_device = int(user_input)
        device_name = midi_devices.pop(which_device)
        inport = mido.open_input(device_name)
        port_dict[device_name] = inport
    except:
        print("please enter an into or nothing to continue")

while 1:
    for device, midi_port in port_dict.iteritems():

        # if two cc messages with the same control and channel have come then only append most recent
        for msg in midi_port.iter_pending():
            print(msg)
示例#25
0
def list_devices():
    return {
        'input': mido.get_input_names(),
        'output': mido.get_output_names(),
    }
示例#26
0
        LED_BRIGHTNESS = 30     # Set to 0 for darkest and 255 for brightest
        LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
        LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

        parser = argparse.ArgumentParser()
        parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
        args = parser.parse_args()

        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        # Initialize the library (must be called once before other functions).
        self.strip.begin()

ledstrip = LedStrip()

ports = mido.get_input_names()

for port in ports:
	if "Through" not in port and "RPi" not in port and "RtMidOut" not in port:
		try:
			inport =  mido.open_input(port)
			print("In-port set to "+port)
		except:
			print ("Failed to set "+port+" as in-port")

green = 120
red = 100
blue = 220

while True:
	for msg in inport.iter_pending():
示例#27
0
import mido
from mido import Message
from pprint import pprint
import mingus.core.chords as chords
import random
from os import system
import time

outport = mido.open_output()

input1 = mido.get_input_names()[0]
for inp in mido.get_input_names():
    if inp.find('Keystation') > -1:
        input1 = inp
"""
Application:

1. random generate chord and type(ex C, dominant)
2. translate with mingus
3. show on screen
4. wait until correctly pressed(or just one chance and show succes/failure)


New features:
ok- say chord name and correct/failed

ok- consider the chord once n notes are playe(n is the number of notes of the current chord), then say right or wrong

- wait until no more notes pressed

- read midi and play it
示例#28
0
def get_available_input_ports():
  """Returns a list of available input MIDI ports."""
  return mido.get_input_names()
示例#29
0
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)
示例#30
0
 def __init__(self, num_keys):
     self.num_keys = num_keys
     self.pixels = NeoPixel(board.D18, self.num_keys)
     self.inputs = mido.get_input_names()
     self.queue = []
     self.pause = False
示例#31
0
import pygame.midi
pygame.midi.init()

import mido
#print(mido.get_input_names())
mido.set_backend('mido.backends.pygame')

#inport = mido.open_input()
print( mido.get_input_names())
inport = mido.open_input()
示例#32
0
文件: main.py 项目: kaos/Llia
parser.add_argument("--nosplash", action="store_false", help=HM_NO_SPLASH)
parser.add_argument("--norepl", action="store_false", help=HM_NO_REPL)

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)
示例#33
0
def main():
    print(mido.get_input_names())
示例#34
0
def print_midi_info():
    print()
    print_ports('Input MIDI Ports:', mido.get_input_names())
    print_ports('Output MIDI Ports:', mido.get_output_names())
示例#35
0
 def getAllMidiInputs(self):
     try:
         return mido.get_input_names()
     except Exception as e:
         print("Impossible to run mido_get_output_names", e)
         return []
示例#36
0
文件: tk_splash.py 项目: plewto/Llia
 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)
示例#37
0
 def list_devices(self):
     return mido.get_input_names()
示例#38
0
                    if msg.control != ignore:
                        midicallback(msg)
                        savetime1 = time.time()
            if time.time() - savetime1 > 3:
                savetime1 = time.time()
                ignore = 255
        except KeyboardInterrupt:
            print("Exiting")
            sys.exit()
            break

if __name__ == "__main__":
    print("MIDItoOBS made by lebaston100.de")
    print("!!MAKE SURE OBS IS RUNNING OR THIS SCRIPT WILL CRASH!!")
    print("Select Midi Device")
    deviceList = mido.get_input_names()
    counter = 0
    for device in deviceList:
        print("%s: %s" % (counter, device))
        counter += 1
    input_select = int(input("Select 0-%s: " % str(len(deviceList)-1)))
    if input_select in range(0, len(deviceList)):
        print("You selected: %s (%s)" % (str(input_select), deviceList[input_select]))
        result = db.search(Query().value == deviceList[input_select])
        if result:
                db.remove(Query().type == "device")
                db.insert({"type" : "device", "value": deviceList[input_select]})
        else:
                db.insert({"type" : "device", "value": deviceList[input_select]})
        try:
            midiport = mido.open_input(deviceList[input_select])
示例#39
0
### Create instance of Piano and Recorder
p = Piano()
rec = Recorder()
log = Logger(p, rec)
### Options
verbose = "-v" in argv

### Select input and output devices
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:
示例#40
0
def get_available_input_ports():
    """Returns a list of available input MIDI ports."""
    return mido.get_input_names()
示例#41
0
# this determines how much debugging information gets printed
debug = config.getint('general', 'debug')

try:
    r = redis.StrictRedis(host=config.get('redis', 'hostname'),
                          port=config.getint('redis', 'port'),
                          db=0)
    response = r.client_list()
except redis.ConnectionError:
    print "Error: cannot connect to redis server"
    exit()

# this is only for debugging
print('------ INPUT ------')
for port in mido.get_input_names():
    print(port)
print('-------------------------')

try:
    inputport = mido.open_input(config.get('midi', 'device'))
    if debug > 0:
        print "Connected to MIDI input"
except:
    print "Error: cannot connect to MIDI input"
    exit()

while True:
    time.sleep(config.getfloat('general', 'delay'))

    for msg in inputport.iter_pending():
示例#42
0
#!/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())
示例#43
0
def InConfig():

    print("")
    log.info("MIDIin...")
    print("List and attach to available devices on host with OUT port :")

    if platform == 'darwin':
        mido.set_backend('mido.backends.rtmidi/MACOSX_CORE')

    genericnumber = 0

    for port, name in enumerate(mido.get_input_names()):

        #print()
        # Maxwell midi IN & OUT port names are different

        if name.find("from ") == 0:
            #print ("name",name)
            name = "to " + name[5:]
            #print ("corrected to",name)

        outport = FindOutDevice(name)
        midinputsname[port] = name

        #print()
        # print("name",name, "Port",port, "Outport", outport)
        '''
        # New Bhoreal found ?
        if name.find(BhorealMidiName) == 0:

            try:
                bhorealin, port_name = open_midiinput(outport) # weird rtmidi call port number is not the same in mido enumeration and here

                BhoreralDevice = InObject(port_name, "bhoreal", outport, bhorealin)
                print("BhorealDevice.queue",BhoreralDevice.queue )
                # thread launch to handle all queued MIDI messages from Bhoreal device    
                thread = Thread(target=bhoreal.MidinProcess, args=(bhoreal.bhorqueue,))
                thread.setDaemon(True)
                thread.start()
                print("Attaching MIDI in callback handler to Bhoreal : ",  name, "port", port, "portname", port_name)
                BhoreralDevice.rtmidi.set_callback(bhoreal.AddQueue(port_name))
            except Exception:
                traceback.print_exc()

        '''
        # Bhoreal found ?
        #print(BhorealMidiName, name.find(BhorealMidiName))
        if name.find(BhorealMidiName) > -1:

            try:
                bhorealin, port_name = open_midiinput(
                    outport
                )  # weird rtmidi call port number is not the same in mido enumeration and here
            except (EOFError, KeyboardInterrupt):
                sys.exit

            #print('Bhoreal Found..')
            #midinputs.append(bhorealin)
            InDevice.append(InObject(name, "bhoreal", outport, bhorealin))
            # thread launch to handle all queued MIDI messages from Bhoreal device
            print("Launching Thread for Bhoreal")
            thread = Thread(target=bhoreal.MidinProcess,
                            args=(bhoreal.bhorqueue, ))
            #thread = Thread(target=bhoreal.MidinProcess, args=(InDevice[port].queue,))
            thread.setDaemon(True)
            thread.start()
            #print("midinputs[port]", midinputs[port])
            print(name)
            InDevice[port].rtmidi.set_callback(bhoreal.AddQueue(name))
            #midinputs[port].set_callback(bhoreal.AddQueue(name))
        '''

        # New LaunchPad Mini Found ?
        if name.find(LaunchMidiName) == 0:
   
            
            try:
                launchin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()

            LaunchDevice = InObject(port_name, "launchpad", outport, launchin)
            thread = Thread(target=launchpad.MidinProcess, args=(launchpad.launchqueue,))
            thread.setDaemon(True)
            thread.start()
            print("Attaching MIDI in callback handler to Launchpad : ", name, "port", port, "portname", port_name)
            LaunchDevice.rtmidi.set_callback(launchpad.LaunchAddQueue(name))

        '''

        # Old LaunchPad Mini Found ?
        if name.find(LaunchMidiName) == 0:

            try:
                launchin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            #midinputs.append(launchin)

            #print('Launchpad Found..')
            InDevice.append(InObject(name, "launchpad", outport, launchin))
            print("Launching Thread for Launchpad")
            thread = Thread(target=launchpad.MidinProcess,
                            args=(launchpad.launchqueue, ))
            #thread = Thread(target=launchpad.MidinProcess, args=(InDevice[port].queue,))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(launchpad.LaunchAddQueue(name))
            #launchin.set_callback(launchpad.LaunchAddQueue(name))

        # LPD8 Found ?
        if name.find('LPD8') == 0:

            #print('LPD8 Found..')

            try:
                LPD8in, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            #midinputs.append(LPD8in)
            InDevice.append(InObject(name, "LPD8", outport, LPD8in))
            print("Launching Thread for Launchpad")
            thread = Thread(target=LPD8.MidinProcess, args=(LPD8.LPD8queue, ))
            #thread = Thread(target=LPD8.MidinProcess, args=(InDevice[port].queue,))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(LPD8.LPD8AddQueue(name))

        # DJmp3 Found ?
        if name.find(DJName) == 0:

            #print('DJmp3 Found..')

            try:
                DJin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            InDevice.append(InObject(name, "DJmp3", outport, DJin))
            print("Launching Thread for DJmp3")
            thread = Thread(target=dj.MidinProcess, args=(dj.DJqueue, ))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(dj.DJAddQueue(name))

        # Beatstep Found ?
        if name.find(BeatstepName) == 0:

            #print('Beatstep Found..')

            try:
                Beatstepin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            InDevice.append(InObject(name, "Beatstep", outport, Beatstepin))
            print("Launching Thread for Beatstep")
            thread = Thread(target=beatstep.MidinProcess,
                            args=(beatstep.BEATSTEPqueue, ))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(beatstep.BeatstepAddQueue(name))

        # BCR 2000 Found ?
        if name.find(BCRName) == 0:

            #print('BCR2000 Found..')

            try:
                BCRin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            InDevice.append(InObject(name, "BCR2000", outport, BCRin))
            print("Launching Thread for BCR 2000")
            thread = Thread(target=bcr.MidinProcess, args=(bcr.BCRqueue, ))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(bcr.BCRAddQueue(name))

        # Sequencer Found ?
        if name.find(gstt.SequencerNameOUT) == 0:

            #print('Sequencer Found..')

            try:
                Sequencerin, port_name = open_midiinput(outport)
            except (EOFError, KeyboardInterrupt):
                sys.exit()
            InDevice.append(InObject(name, "Sequencer", outport, Sequencerin))
            print("Launching Thread for Sequencer")
            thread = Thread(target=sequencer.MidinProcess,
                            args=(sequencer.SEQUENCERqueue, ))
            thread.setDaemon(True)
            thread.start()
            # print(name, "port", port, "portname", port_name)
            InDevice[port].rtmidi.set_callback(
                sequencer.SequencerAddQueue(name))

        # Everything that is not Bhoreal, Launchpad, beatstep, Sequencer, LPD8, BCR 2000 or DJmp3
        if name.find(BhorealMidiName) != 0 and name.find(
                LaunchMidiName) != 0 and name.find('LPD8') != 0 and name.find(
                    DJName
                ) != 0 and name.find(BeatstepName) != 0 and name.find(
                    BCRName) != 0 and name.find(gstt.SequencerNameOUT) != 0:

            try:
                #print (name, name.find("RtMidi output"))
                if name.find("RtMidi output") > -1:
                    print("No thread started for device", name)
                else:
                    portin = object
                    port_name = ""
                    portin, port_name = open_midiinput(outport)
                    #midinputs.append(portin)
                    InDevice.append(InObject(name, "generic", outport, portin))

                    thread = Thread(target=MidinProcess,
                                    args=(midinputsqueue[port], port_name))
                    thread.setDaemon(True)
                    thread.start()

                    print("Launching thread for", name, "port", port,
                          "portname", port_name)
                    #midinputs[port].set_callback(AddQueue(name),midinputsqueue[port])
                    #midinputs[port].set_callback(AddQueue(name))
                    #genericnumber += 1
                    InDevice[port].rtmidi.set_callback(AddQueue(name, port))

            except Exception:
                traceback.print_exc()

    #print("")
    print(InObject.counter, "In devices")
示例#44
0
import fastopc, time
import numpy as np
import mido
import time

####################################################
inputNames = mido.get_input_names()
print(inputNames)
inport = mido.open_input(inputNames[1])
sleepTime = 1.e-4
####################################################


class Board:
    def __init__(self):
        self.knobs = np.zeros(8)
        self.pitchwheel = 0.0
        self.notes = np.zeros(128)

    def update(self, msg):
        if msg.type == 'note_on':
            self.notes[msg.note] = 1
        elif msg.type == 'note_off':
            self.notes[msg.note] = 0
        elif msg.type == 'pitchwheel':
            self.pitchwheel = msg.pitch
        elif msg.type == 'control_change':
            self.knobs[msg.control] = msg.value


board = Board()
示例#45
0
def main_app(offline: bool):
    global_storage = GlobalStorage()
    sm = None
    aq = None
    ae = None
    if not offline:
        sm = SimConnect()
        aq = AircraftRequests(sm, _time=200)
        ae = AircraftEvents(sm)
        global_storage.set_aircraft_events(ae)
        global_storage.set_aircraft_requests(aq)
    else:
        global_storage.set_aircraft_events(MockAircraftEvents())
        global_storage.set_aircraft_requests(MockAircraftRequests())

    print('Midi input devices:', mido.get_input_names())
    print('Midi output devices:', mido.get_output_names())
    selected_input = ConfigFile.get_midi_input()
    selected_output = ConfigFile.get_midi_output()
    print('Using midi input device:', selected_input)
    print('Using midi output device:', selected_output)

    aircraft = aq.get('TITLE')
    print("Current aircraft:", aircraft)
    outport = mido.open_output(selected_output)  # pylint: disable=no-member

    control_change_dict = {}
    note_dict = {}

    def handle_message(msg: mido.Message):
        # print(msg)
        if msg.type == 'control_change':
            if msg.control in control_change_dict:
                control_change_dict[msg.control].on_cc_data(msg.value)
        elif msg.type == 'note_on':
            if msg.note in note_dict:
                note_dict[msg.note].on_note_data(True)
        elif msg.type == 'note_off':
            if msg.note in note_dict:
                note_dict[msg.note].on_note_data(False)

    inport = mido.open_input(selected_input, callback=handle_message)  # pylint: disable=no-member

    for e in range(1, 17):
        encoder = RotaryEncoder(e, outport)
        global_storage.add_encoder(encoder)

    for b in range(1, 33):
        btn = PushButton(b, outport)
        global_storage.add_button(btn)

    for f in range(1, 3):
        fader = Fader(f)
        global_storage.add_fader(fader)

    c = ConfigFile(aircraft)
    c.configure()
    triggers = c.triggers

    for encoder in GlobalStorage().encoders:
        control_change_dict[encoder.rotary_control_channel] = encoder
        note_dict[encoder.button_note] = encoder

    for btn in GlobalStorage().buttons:
        note_dict[btn.button_note] = btn

    for f in GlobalStorage().faders:
        control_change_dict[f.control_channel] = f

    while True:
        for obj in GlobalStorage().all_elements:
            if obj.bound_simvar and aq:
                sv = aq.get(obj.bound_simvar)
                obj.on_simvar_data(sv)

        current_aircraft = aq.get('TITLE')
        if current_aircraft and aircraft != current_aircraft:
            print("Aircraft changed from", aircraft, "to", current_aircraft)
            break
        time.sleep(0.05)

    global_storage.clear()
    inport.close()
    outport.close()
示例#46
0
def openIn(deviceName):
    inputPort = chooseDevice(mido.get_input_names(), deviceName)
    if inputPort:
        return mido.open_input(inputPort)
    else: 
        return None
示例#47
0
    r = redis.StrictRedis(host=config.get('redis','hostname'), port=config.getint('redis','port'), db=0)
    response = r.client_list()
except redis.ConnectionError:
    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('-------------------------')

# the scale and offset are used to map MIDI values to Redis values
scale  = patch.getfloat('output', 'scale', default=127)
offset = patch.getfloat('output', 'offset', default=0)

try:
    inputport  = mido.open_input(patch.getstring('midi', 'device'))
    if debug>0:
        print("Connected to MIDI input")
except:
    print("Error: cannot connect to MIDI input")
    exit()
Writer = animation.writers['ffmpeg']  #avconv
writer = Writer(fps=15, metadata=dict(artist=name), bitrate=1800)

network_pkl = '/home/romain/win_desk/stylegan2/results/00098-stylegan2-feuilles1k-1gpu-config-e/network-snapshot-000600.pkl'
G, _D, Gs = pretrained_networks.load_networks(network_pkl)

truncation_psi = 1.0
w, h = 256, 256
seed = 45
rand = np.random.RandomState(seed)
# src_seeds=[639,701,687,615,2268]
# dst_seeds=[888,829,1898,1733]
# style_ranges=[range(0,4)]*3+[range(4,8)]*2+[range(8,14)]
loop, reset = True, False
midi_name = 'Midi Fighter Twister:Midi Fighter Twister MIDI 1 28:0'
assert midi_name in mido.get_input_names()

Gs_kwargs = dnnlib.EasyDict()
Gs_kwargs.output_transform = dict(func=tflib.convert_images_to_uint8,
                                  nchw_to_nhwc=True)
Gs_kwargs.randomize_noise = False
if truncation_psi is not None:
    Gs_kwargs.truncation_psi = truncation_psi

latent = np.array([rand.randn(Gs.input_shape[1])])
dlatent = Gs.components.mapping.run(latent, None)  # [seed, layer, component]
images = Gs.components.synthesis.run(dlatent, **Gs_kwargs)


def press(event):
    global loop, reset
#

# set up backend
mido.set_backend('mido.backends.rtmidi')

# system command to set up the midi thru port
# TODO would be nice to do this in python, but
# rtmidi has issues seeing ports it has created
#os.system(runCmd)
amidiProc = subprocess.Popen(['amidithru', name])
#print("launched amidithru with pid %s" % amidiProc.pid)

# regex to match on rtmidi port name convention
nameRegex = "(" + name + ":" + name + "\s+\d+:\d+)"
matcher = re.compile(nameRegex)
newList = list(filter(matcher.match, mido.get_input_names()))
input_name = newList[0]

inport = mido.open_input(input_name)


def uptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        return uptime_seconds


# keep running and watch for midi cc
while True:
    time.sleep(.01)
    while inport.pending():
def main(port):
	if (port is None):
		print ('Available MIDI ports')
		print (mido.get_input_names())
	else:
		listen(port)
示例#51
0
def list_input_devices():
    return mido.get_input_names()
示例#52
0
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))
示例#53
0
    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)
示例#54
0
import os, sys, inspect
currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

import mido
import time
from modules.midiHelper import *

midiPort = mido.get_input_names()[0]
midiIN = mido.open_input(midiPort)
midiOUT = mido.open_output(midiPort)

print("~~~~~ Moving vPot up ~~~~~~")
ch = 0
cc = [16, 17, 18, 19, 20, 21, 22, 23][ch]
# first IP block
for i in range(0, 127):
    msg = mido.Message('control_change', control=16, value=1)
    midiOUT.send(msg)
    time.sleep(0.01)
time.sleep(0.2)
# 2nd IP block
for i in range(0, 27):
    msg = mido.Message('control_change', control=17, value=1)
    midiOUT.send(msg)
    time.sleep(0.01)
for i in range(0, 27):
    msg = mido.Message('control_change', control=17, value=65)
    midiOUT.send(msg)
示例#55
0
#!/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())
示例#56
0
文件: midido.py 项目: wSzki/rytm
import mido
from mido import Message
msg = Message('note_on', note=60)
print(msg)

name = mido.get_input_names()
print(name)

inport = mido.open_input(name[0])
print(inport)
msg = inport.receive()
for msg in inport:
    print(msg)
print(msg)
示例#57
0
def initialize_MIDI_inout():
    """Initialize a MIDI input and 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()
    inports = mido.get_input_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.
    outport = None
    for name in outports:
        if re.match(r'mio', name):
            try:
                outport = mido.open_output(name)
                break
            except:
                pass

    if not outport:
        for name in outports:
            try:
                outport = mido.open_output(name)
                break
            except:
                pass

    if not outport:
        print("Sorry, unable to open any MIDI output port.")
        sys.exit(1)

    # Now try to pick the right port to input 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.
    inport = None
    for name in inports:
        if re.match(r'mio', name):
            try:
                inport = mido.open_input(name)
                break
            except:
                pass

    if not inport:
        for name in inports:
            try:
                inport = mido.open_input(name)
                break
            except:
                pass

    if not inport:
        print("Sorry, unable to open any MIDI input port.")
        sys.exit(1)

    return (inport, outport)
示例#58
0
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()))
示例#59
0
文件: play.py 项目: gelendir/pits
def devices():
    for device in mido.get_input_names():
        print(device)
示例#60
0
    def available_ports(cls, output=True):
        if output:
            return mido.get_output_names()

        return mido.get_input_names()