Example #1
0
def open_midi_io():
    port_num = 0
    for i, name in enumerate(mido.get_ioport_names()):
        usb_match = re.search("USB", name)
        if usb_match:
            port_num = i
            break

    port = mido.open_ioport(mido.get_ioport_names()[port_num])
    return port
Example #2
0
    def open_midi_io(self, port_num=None):
        ''' Open first USB Midi IO port available. Use port_num = # to specify a number.'''
        if port_num == None:
            for i, name in enumerate(mido.get_ioport_names()):
                usb_match = re.search("USB", name)
                if usb_match:
                    port_num = i
                    break

        port = mido.open_ioport(mido.get_ioport_names()[port_num])
        return port
Example #3
0
def setup():
    portnames = mido.get_ioport_names()
    p = mido.open_ioport(portnames[1])

    # enter programmer mode
    p.send(mido.Message("sysex", data=[0, 32, 41, 2, 16, 44, 3]))
    return p
Example #4
0
 def detect_devices(self, initial=True):
     from launchpad import LaunchpadMK2, LaunchpadPro, LaunchpadS
     from keyboard import Keyboard
     logging.debug("Enumerating MIDI ports...")
     configured_ports = {grid.grid_name for grid in self.grids}
     try:
         detected_ports = set(mido.get_ioport_names())
     except:
         logging.exception("Error while enumerating MIDI ports")
         detected_ports = set()
     for port_name in detected_ports - configured_ports:
         # Detected a new device! Yay!
         klass = None
         if "Launchpad Pro MIDI 2" in port_name:
             klass = LaunchpadPro
         if "Launchpad MK2" in port_name:
             klass = LaunchpadMK2
         if "Launchpad S" in port_name:
             klass = LaunchpadS
         if "Launchpad Mini" in port_name:
             klass = LaunchpadS
         if "reface" in port_name:
             klass = Keyboard
         if klass is not None:
             # FIXME find a better way than this for hotplug!
             if not initial:
                 logging.info(
                     "Detected hotplug of new device: {}".format(port_name))
                 time.sleep(4)
             self.grids.append(klass(self, port_name))
     for port_name in configured_ports - detected_ports:
         # Removing a device
         logging.info("Device {} is no longer plugged. Removing it.".format(
             port_name))
         self.grids = [g for g in self.grids if g.grid_name != port_name]
Example #5
0
 def __init__(self):
     for port in mido.get_ioport_names():
         if port.startswith(self._PORT_PREFIX):
             self._port = mido.open_ioport(port)
             break
     else:
         raise RuntimeError("Could not find a port named '%s'" % self._PORT_PREFIX)
Example #6
0
    def __init__(self, device, deviceid):
        self.log = get_logger("midi_to_obs_device")
        self._id = deviceid
        self._devicename = device["devicename"]
        self._port_in = 0
        self._port_out = 0

        try:
            self.log.debug("Attempting to open midi port `%s`" % self._devicename)
            # a device can be input, output or ioport. in the latter case it can also be the other two
            # so we first check if we can use it as an ioport
            if self._devicename in mido.get_ioport_names():
                self._port_in = mido.open_ioport(name=self._devicename, callback=self.callback, autoreset=True)
                self._port_out = self._port_in
            # otherwise we try to use it separately as input and output
            else:
                if self._devicename in mido.get_input_names():
                    self._port_in = mido.open_input(name=self._devicename, callback=self.callback)
                if self._devicename in mido.get_output_names():
                    self._port_out = mido.open_output(name=self._devicename, callback=self.callback, autoreset=True)
        except:
            self.log.critical("\nCould not open device `%s`" % self._devicename)
            self.log.critical("The midi device might be used by another application/not plugged in/have a different name.")
            self.log.critical("Please close the device in the other application/plug it in/select the rename option in the device management menu and restart this script.")
            self.log.critical("Currently connected devices:")
            for name in mido.get_input_names():
                self.log.critical("  - %s" % name)
            # EIO 5 (Input/output error)
            exit(5)
Example #7
0
 def tick(self, tick):
     from launchpad import LaunchpadMK2, LaunchpadPro, LaunchpadS
     from keyboard import Keyboard
     if tick % 100 == 1:
         configured_ports = {grid.grid_name for grid in self.grids}
         detected_ports = set(mido.get_ioport_names())
         for port_name in detected_ports - configured_ports:
             # Detected a new device! Yay!
             klass = None
             if "Launchpad Pro MIDI 2" in port_name:
                 klass = LaunchpadPro
             if "Launchpad MK2" in port_name:
                 klass = LaunchpadMK2
             if "Launchpad S" in port_name:
                 klass = LaunchpadS
             if "Launchpad Mini" in port_name:
                 klass = LaunchpadS
             if "reface" in port_name:
                 klass = Keyboard
             if klass is not None:
                 # FIXME find a better way than this for hotplug!
                 if tick > 1:
                     logging.info(
                         "Detected hotplug of new device: {}".format(
                             port_name))
                     time.sleep(4)
                 self.grids.append(klass(self, port_name))
         for port_name in configured_ports - detected_ports:
             # Removing a device
             logging.info(
                 "Device {} is no longer plugged. Removing it.".format(
                     port_name))
             self.grids = [
                 g for g in self.grids if g.grid_name != port_name
             ]
Example #8
0
 def _gui_select_ioport(self):
     ioport_names = get_ioport_names()
     for i in range(len(ioport_names)):
         print('%.2i:\t%s' % (i, ioport_names[i]))
     ioport_num = int(input('Enter number of MIDI interface: '))
     try:
         return ioport_names[ioport_num]
     except OSError as errmsg:
         print(errmsg)
Example #9
0
    def getDevice(self):
        portnames = mido.get_ioport_names()

        # Filter for LPD8 devices that aren't yet occupied by class-instances
        portnames = [x for x in portnames if x.startswith("LPD8:LPD8")]

        if portnames:
            self.port = mido.open_ioport(portnames[0])
        else:
            raise Exception("No free LPD8 devices left")
Example #10
0
 def load_devices(self):
     self.device_liststore.clear()
     i = 0
     for port in mido.get_ioport_names():
         logger.debug('Adding port {:s}...'.format(port))
         self.device_liststore.append([port])
         if i == 0:
             logger.debug('Port {:s} is active'.format(port))
             self.device.set_active(i)
         i += 1
Example #11
0
def main():
    if len(sys.argv) > 1:
        portname = sys.argv[1]
    else:
        try:
            portname = next(name for name in mido.get_ioport_names() if name.startswith("APC MINI MIDI"))
        except StopIteration:
            portname = None  # Use default port

    app = ApcMiniApp(light_behaviour=TOGGLE)
    app.open_input(portname)
    app.run()
Example #12
0
def main():
    p = argparse.ArgumentParser()
    p.add_argument('-p', '--port-name', dest='port_name')
    p.add_argument('--stdout', dest='stdout', action='store_true')
    p.add_argument('--store', dest='store', action='store_true')
    p.add_argument('-n',
                   '--num',
                   dest='num',
                   type=int,
                   default=1,
                   help='Preset number (if --store is used)')
    args = p.parse_args()
    if args.stdout:
        args.port_name = '__stdout__'
    elif not args.port_name:
        all_io_ports = set(mido.get_ioport_names())
        bcf_ports = [name for name in all_io_ports if 'BCF2000' in name]
        non_loop = [
            name for name in all_io_ports if 'through' not in name.lower()
        ]
        if len(bcf_ports) == 1:
            args.port_name = bcf_ports[0]
        elif len(non_loop) == 1:
            args.port_name = non_loop[0]
        else:
            raise Exception(
                f'Could not find suitable port from "{all_io_ports}"')
    logger.info(f'Sending to {args.port_name}...')
    pst = build_preset()
    if args.stdout:

        def print_output(obj: Union[BCLBlock, Preset]):
            if isinstance(obj, Preset):
                obj = obj.build_bcl_block()
            for item in obj.build_sysex_items():
                print(item.bcl_text)

        print_output(pst)
        if args.store:
            blk = pst.build_store_block(args.num)
            print_output(blk)
    else:
        asyncio.run(pst.send_to_port_name(args.port_name, args.store,
                                          args.num))
        log_msg = f'Preset sent to {args.port_name}'
        if args.store:
            log_msg = f'{log_msg} and store as preset {args.num}'
        logger.success(log_msg)
Example #13
0
def print_diagnostics():
    input_names = mido.get_input_names()
    ioport_names = mido.get_ioport_names()
    output_names = mido.get_output_names()

    print('MIDI input ports:')
    for i, ins in enumerate(input_names):
        print('  {} {}'.format(i, ins))

    print('MIDI I/O ports:')
    for i, ios in enumerate(input_names):
        print('  {} {}'.format(i, ios))

    print('MIDI output ports:')
    for i, outs in enumerate(input_names):
        print('  {} {}'.format(i, outs))
Example #14
0
    def __init__(self, name='', channel=0):
        """
        Initialise a connection to a MIDI device.

        Makes a connection to the first MIDI device matching the substring.
        Args:
            name (str): Substring of the device name, to match.
            channel (int): MIDI channel this controller uses. 

        Note that this requires all controls on this device to use the same channel.
        """
        devices = [i for i in mido.get_ioport_names() if name in i]
        if len(devices) == 0:
            sys.exit('No controller devices found!')
        if len(devices) > 1:
            sys.stderr.write(
                'Warning: multiple possible controller devices found: {}. Selecting first one.\n'
                .format(devices))
        device = devices[0]
        self.midi_port = mido.open_ioport(device, autoreset=True)
        self.channel = channel
        self.controls = dict()
        self.leds = dict()
        self.event_queue = OrderedDict()
Example #15
0
        pygame.event.pump()

        if pygame.event.peek():
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                if event.type == pygame.KEYDOWN:
                    running = False 

        self.clock.tick(self.fps)
        return running

cb = False

devices = mido.get_ioport_names()
numark_devname = None
print('MIDI devices:')
for device in devices:
    print('* ' + device)
    if device.startswith('Numark Mix Track'):
      print('  Mix Track found!')
      numark_devname = device

if numark_devname is None:
    print("Couldn't find a Mix Track, exiting.")
    exit(1)

# For PC:
opts = pygame.HWSURFACE | pygame.FULLSCREEN | pygame.DOUBLEBUF
# For other
Example #16
0
import mido
from mido import Message as M

m_out = mido.open_ioport(mido.get_ioport_names()[0])

while True:
    for i in m_out.iter_pending():
        print i
Example #17
0
File: Midi File.py Project: udz/py
import mido

print('List of in ports')
print(mido.get_input_names())

print('List of IO ports')
print(mido.get_ioport_names())

print('List of out ports')
print(mido.get_output_names())

mido.write_syx_file
# Midi File Functions

# Load MIDI file
outport = mido.open_output('Microsoft GS Wavetable Synth 0')
#outport = mido.open_output('CASIO USB-MIDI 1')
#outport = mido.open_output('Android 1')

outport.panic()
#mid = mido.MidiFile('abc.mid')
mid = mido.MidiFile('Ace_of_Base_-_All_That_She_Wants.mid')

# Play MIDI file
for msg in mid.play():
    outport.send(msg)

# Print messages contained in the MIDI file
'''
for i, track in enumerate(mid.tracks):
    print('Track {}: {}'.format(i, track.name))
Example #18
0
def get_ports():
    return mido.get_ioport_names()
Example #19
0
 def discover(self):
     for name in mido.get_ioport_names():
         if name.startswith('nanoKONTROL2'):
             LOG.info('found port %s', name)
             return name
Example #20
0
def get_ports():
    filtered = []
    for p in mido.get_ioport_names():
        if 'MicroBrute' in p:
            filtered.append(p)
    return filtered
Example #21
0
 def findPortsForModel(cls, model):
     ports = list()
     for port in mido.get_ioport_names():
         if port.startswith(model._PORT_PREFIX):
             ports = ports + [(port, model)]
     return ports
Example #22
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        # Set up MIDI connection
        ports = mido.get_ioport_names()
        self.midi_port_combo.addItems(ports)
        self.midi_port_combo.currentIndexChanged.connect(
            self.on_midi_port_changed)
        self.midi_port = None
        self.on_midi_port_changed()

        # Connect the DCO Controls
        self.dco_range_4_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(6, 0))
        self.dco_range_8_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(6, 1))
        self.dco_range_16_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(6, 2))
        self.dco_range_32_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(6, 3))
        self.dco_pw_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(14, self.dco_pw_slider.value()))
        self.dco_pwm_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(15, self.dco_pwm_slider.value()))
        self.dco_pulse_off_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(3, 0))
        self.dco_pulse_sq_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(3, 1))
        self.dco_pulse_pw_fix_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(3, 2))
        self.dco_pulse_pwpwm_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(3, 3))
        self.dco_saw_off_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 0))
        self.dco_saw_saw_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 1))
        self.dco_saw_pw_fix_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 2))
        self.dco_saw_pwpwm_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 3))
        self.dco_saw_saw_alt1_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 4))
        self.dco_saw_saw_alt2_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(4, 5))
        self.dco_sub_sq_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 0))
        self.dco_sub_pw_fix_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 1))
        self.dco_sub_sq_alt1_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 2))
        self.dco_sub_sq_alt2_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 3))
        self.dco_sub_sub_sq_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 4))
        self.dco_sub_sub_pw_fix_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(5, 5))
        self.dco_sub_lvl_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(7, self.dco_sub_lvl_slider.value()))
        self.dco_noise_lvl_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(8, self.dco_noise_lvl_slider.value(
            )))
        self.dco_lfo_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(11, self.dco_lfo_slider.value()))
        self.dco_after_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(13, self.dco_after_slider.value()))
        self.dco_env_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(12, self.dco_env_slider.value()))
        self.dco_env_mode_env_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(0, 0))
        self.dco_env_mode_inv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(0, 1))
        self.dco_env_mode_denv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(0, 2))
        self.dco_env_mode_dinv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(0, 3))

        # Connect the VCF controls
        self.vcf_hpf_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(9, self.vcf_hpf_slider.value()))
        self.vcf_freq_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(16, self.vcf_freq_slider.value()))
        self.vcf_res_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(17, self.vcf_res_slider.value()))
        self.vcf_lfo_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(18, self.vcf_lfo_slider.value()))
        self.vcf_key_flw_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(20, self.vcf_key_flw_slider.value()
                                           ))
        self.vcf_after_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(21, self.vcf_after_slider.value()))
        self.vcf_env_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(19, self.vcf_env_slider.value()))
        self.vcf_env_mode_env_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(1, 0))
        self.vcf_env_mode_inv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(1, 1))
        self.vcf_env_mode_denv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(1, 2))
        self.vcf_env_mode_dyn_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(1, 3))

        # Connect the ENV controls
        self.env_t1_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(26, self.env_t1_slider.value()))
        self.env_l1_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(27, self.env_l1_slider.value()))
        self.env_t2_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(28, self.env_t2_slider.value()))
        self.env_l2_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(29, self.env_l2_slider.value()))
        self.env_t3_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(30, self.env_t3_slider.value()))
        self.env_l3_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(31, self.env_l3_slider.value()))
        self.env_t4_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(32, self.env_t4_slider.value()))
        self.env_key_flw_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(33, self.env_key_flw_slider.value()
                                           ))

        # Connect the VCA controls
        self.vca_level_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(22, self.vca_level_slider.value()))
        self.vca_after_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(23, self.vca_after_slider.value()))
        self.vca_env_mode_env_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(2, 0))
        self.vca_env_mode_gt_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(2, 1))
        self.vca_env_mode_denv_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(2, 2))
        self.vca_env_mode_dgt_rbutton.pressed.connect(
            lambda: self.on_sysex_send_ipr(2, 3))

        # Connect the LFO controls
        self.lfo_rate_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(24, self.lfo_rate_slider.value()))
        self.lfo_delay_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(25, self.lfo_delay_slider.value()))

        # Connect the CHORUS controls
        self.chorus_checkBox.stateChanged.connect(
            lambda: self.on_sysex_send_ipr(10, self.chorus_checkBox.isChecked(
            )))
        self.chorus_rate_slider.valueChanged.connect(
            lambda: self.on_sysex_send_ipr(34, self.chorus_rate_slider.value()
                                           ))

        # Set up validation and connect the patch name editor
        name_reg_ex = QRegExp("[A-Za-z0-9 -]*")
        input_validator = QRegExpValidator(name_reg_ex,
                                           self.patch_name_lineEdit)
        self.patch_name_lineEdit.setValidator(input_validator)
        self.patch_name_lineEdit.textChanged.connect(
            lambda: self.on_sysex_send_ipr(36, self.patch_name_lineEdit.text()
                                           ))

        # File menu
        self.action_quit.triggered.connect(lambda: sys.exit())
Example #23
0
def get_ports():
    return mido.get_ioport_names()
Example #24
0
    midifile = mido.MidiFile(filename)

    print("Playing ", midifile)
    try:
        for msg in midifile.play():
            port.send(msg)
            app.update()

    except (KeyboardInterrupt, SystemExit):
        print("Program Ended")
        port.panic()
        port.close()

    port.close()


if __name__ == "__main__":
    root = tk.Tk()
    port = mido.open_ioport(mido.get_ioport_names()[1])

    app = Application()
    app.master.title('Sample application')
    app.update()

    #Tk().withdraw()
    filenames = askopenfilenames(initialdir='/home/pi/MIDIMusic/MIDI_Files',
                                 filetypes=[('MIDI Files', '*.mid*')])

    for fn in filenames:
        print(fn)
        playMidi(fn)
Example #25
0
#!/usr/bin/env python3

import mido
import sys

midi_devs = mido.get_ioport_names()

if len(sys.argv) < 2:
    print("Usage: " + sys.argv[0] +
          " MIDI_device_no [file_prefix (e.g., 'P-')]")
    print("\nMidi devices:")
    for i in range(len(midi_devs)):
        print(str(i) + ": " + midi_devs[i])
    sys.exit(0)

if len(sys.argv) == 3:
    file_prefix = sys.argv[2]
else:
    file_prefix = ''

port = mido.open_input(midi_devs[int(sys.argv[1])])

for bank in range(1, 9):
    for number in range(1, 9):
        while True:
            msg = port.receive()
            if msg.type == 'sysex':
                if (msg.data[0] == 65 and msg.data[1] == 53
                        and msg.data[2] == 0 and msg.data[3] == 35
                        and msg.data[4] == 32):
                    file_name = file_prefix + str(bank) + str(number) + ' '