Exemple #1
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
Exemple #2
0
 def connect(self, device):
     logger.debug('Connecting...')
     try:
         self.disconnect()
         self.port = mido.open_ioport(device)
     except IOError as e:
         logger.error('IOError while connecting: "{:s}"'.format(str(e)))
Exemple #3
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)
Exemple #4
0
def save_chords_interactively(port_string, save_file):
    try:
        port = mido.open_ioport(port_string)
    except:
        print("'{}' is not a valid port. Please change the midi port.".format(port_string))
        exit(1)
    try:
        chords = []
        while True:
            print("Please play a chord.")
            chord = read_chord(port)
            print("Your chord:")
            note_processing.print_chord(chord)
            print("Num notes:")
            print(len(chord))
            answer = raw_input("Save? ([Y]/n)")
            if not answer or answer.lower=='y':
                chords.append(chord)
    except KeyboardInterrupt:
        try:
            if os.path.isfile(save_file):
                with open(save_file, 'r') as f:
                    previous_data = pickle.load(f)
            else:
                previous_data = []
            with open(save_file, 'w') as f:
                pickle.dump(previous_data+chords, f)
        except Exception as e: # debugging
            import IPython as ipy
            ipy.embed()
Exemple #5
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)
Exemple #6
0
 def open_port(self, key, port_name, virtual):
     print("OPENING PORT: {} : {} (Virtual:{})".format(
         key, port_name, virtual))
     #cb = partial(self.process_midi, key)
     if key in self.midi_devs.keys():
         print("Already exists")
         return  #Rethink later
     midi_dev = mido.open_ioport(name=port_name, virtual=virtual)
     self.midi_devs[key] = midi_dev
Exemple #7
0
 def __init__(self, src):
     self.q = Queue(1)
     self.thread = Thread(target=self.do_callback)
     self.thread.start()
     try:
         self.midi = mido.open_ioport(src, callback=self.callback)
     except:
         print('Can not open MIDI device, try one of these:')
         print(mido.get_output_names())
Exemple #8
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
Exemple #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")
Exemple #10
0
    def __init__(self, name=None, midi_in_cb=None):
        if name is None:
            name = self.discover()

        if name is None:
            raise exc.NoDeviceError()

        self._port = mido.open_ioport(name)

        if midi_in_cb:
            self._in.callback = midi_in_cb
Exemple #11
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
Exemple #12
0
def debug_io(port_string):
    try:
        port = mido.open_ioport(port_string)
    except:
        print("'{}' is not a valid port. Please change the midi port.".format(port_string))
        exit(1)
    while True:
        print("Please play a chord.")
        chord = read_chord(port)
        print("Your chord:")
        note_processing.print_chord(chord)
        print("Num notes:")
        print(len(chord))
Exemple #13
0
 def connect(self):
     """Connect to the MicroBrute."""
     logger.debug('Connecting...')
     try:
         self.port = mido.open_ioport('MicroBrute MIDI 1')
         logger.debug('Handshaking...')
         self.tx_message(INIT_MSG)
         response = self.rx_message()
         if response[0:11] == MICROBRUTE_MSG_WO_VERSION:
             self.sw_version = '.'.join([str(i) for i in response[11:15]])
             logger.debug(HANDSHAKE_MSG.format(self.sw_version))
         else:
             logger.debug('Bad handshake. Disconnecting...')
             self.disconnect()
     except IOError as e:
         logger.error('IOError while connecting')
Exemple #14
0
 def connect(self, device):
     """Connect to the MicroBrute."""
     logger.debug('Connecting...')
     try:
         self.port = mido.open_ioport(device)
         logger.debug('Handshaking...')
         self.tx_message(INIT_MSG)
         response = self.rx_message()
         if response[0:11] == MICROBRUTE_MSG_WO_VERSION:
             self.sw_version = '.'.join([str(i) for i in response[11:15]])
             logger.debug(HANDSHAKE_MSG.format(self.sw_version))
         else:
             logger.debug('Bad handshake. Disconnecting...')
             self.disconnect()
     except IOError as e:
         logger.error('IOError while connecting: "{:s}"'.format(str(e)))
         self.disconnect()
Exemple #15
0
 def connect(self, device):
     """Connect to the MicroBrute."""
     logger.debug('Connecting to %s...', device)
     try:
         self.port = mido.open_ioport(device)
         logger.debug('Mido backend: %s', str(mido.backend))
         logger.debug('Handshaking...')
         self.tx_message(INQUIRY_REQ)
         response = self.rx_message()
         if response[0:11] == INQUIRY_RES_WO_VERSION:
             self.sw_version = '.'.join([str(i) for i in response[11:15]])
             logger.debug('Handshake ok. Version %s.', self.sw_version)
             self.set_channel(self.get_parameter(RX_CHANNEL))
         else:
             logger.debug('Bad handshake. Disconnecting...')
             self.disconnect()
     except IOError as e:
         logger.error('IOError while connecting: "%s"', str(e))
         self.disconnect()
Exemple #16
0
 def connect(self, device, callback):
     """Connect to the Phatty."""
     logger.debug('Connecting to {:s}...'.format(device))
     try:
         self.port = mido.open_ioport(device)
         self.callback = callback
         self.port.send = self.send
         logger.debug('Handshaking...')
         self.tx_message(INIT_MSG)
         response = self.rx_message()
         self.port.callback = self.process_message
         if response[0:9] == PHATTY_MSG_WO_VERSION:
             self.sw_version = '.'.join([str(i) for i in response[9:13]])
             logger.debug(HANDSHAKE_MSG.format(self.sw_version))
         else:
             logger.debug('Bad handshake. Disconnecting...')
             self.disconnect()
     except IOError as e:
         logger.error('IOError while connecting: "{:s}"'.format(str(e)))
         self.disconnect()
Exemple #17
0
def main(port_string):
    with open('data/chord_bank.pickle', 'r') as f:
        chords = unique(pickle.load(f))
    np.random.shuffle(chords)
    try:
        port = mido.open_ioport(port_string)
    except:
        print "'{}' is not a valid port. Please change the midi port.".format(
            port_string)
        exit(1)
    test = [chord for chord in chords if len(chord) == 3]
    for chord in test:
        notes_io.play_chord(chord, port)
        user_chord = notes_io.read_chord(port)
        if chord_match(user_chord, chord):
            print "You got it right!"
        else:
            print "You missed this one. You played:"
            print note_processing.print_chord(user_chord)
            print "Here's the right answer:"
            print note_processing.print_chord(chord)
        time.sleep(3)
Exemple #18
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()
Exemple #19
0
 def start(self, name, channel, control):
     self.midi_device = mido.open_ioport(name)
     self.channel = channel
     self.control = control
     self._isRunning = True
Exemple #20
0
 def __init__(self, portName, modelClass):
     self._port = mido.open_ioport(portName)
     self.modelClass = modelClass
Exemple #21
0
#!/usr/bin/python

import mido, sys, time

turn_off_map = {}

piano = mido.open_ioport('CASIO USB-MIDI:CASIO USB-MIDI MIDI 1')

midi = mido.MidiFile(sys.argv[1])
chords = []
for event in midi:
    if event.type != 'note_on': continue
    if event.velocity == 0: continue
    if event.time != 0 or not chords: chords.append([])
    chords[-1].append(event.note)

enabled = False
i = 0


def get_voicing(event):
    global i
    if enabled and event.note == max(chords[i]):
        result = chords[i]
        i = (i + 1) % len(chords)
        return result
    return []  # [event.note] if local control is off


while True:
    event = piano.receive()
        message_value = None

        if "note" in message_type:
            message_value = msg.note
        else:
            #NOT A NOTE D:<
            return None

        if  ctrl_on:
            return (message_type, message_value, shift_on, ctrl_on)
        else:
            return (message_type, message_value, shift_on)
    return None


with mido.open_ioport(controller_name) as io:
    last_shift = None
    last_ctrl = None

    def shift_on():
        if last_shift:
            taipu,note,*rest= last_shift
            if taipu == 'note_on':
                #naicu! :)
                if note == 60:
                    return True
        return False

    def ctrl_on():
        if last_ctrl:
            taipu,note,*rest= last_ctrl
Exemple #23
0
import mido
import os

PORT = 'VMini:VMini MIDI 1 20:0'

if __name__ == '__main__':
    print(mido.get_ioport_names())
    port = mido.open_ioport(PORT)

    while True:
        r = port.receive()
        if r.type == 'control_change' and r.channel == 0 and r.control == 14:
            print(r.value)
            os.system(('pactl set-sink-volume 0 %d' % r.value) + '%')

    port.close()
Exemple #24
0
 def __init__(self, ioport_name=None):
     if ioport_name is None:
         ioport_name = self._gui_select_ioport()
     self.port = open_ioport(ioport_name)
Exemple #25
0
 def on_midi_port_changed(self):
     if self.midi_port is not None:
         self.midi_port.close()
     self.midi_port = mido.open_ioport(self.midi_port_combo.currentText(),
                                       callback=self.on_midi_receive)
Exemple #26
0
    def start(self):
        self.midiport = mido.open_ioport(self.midi_port)

        self.midithread = threading.Thread(target=self.midi, daemon=True)
        self.midithread.start()
Exemple #27
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)
Exemple #28
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
Exemple #29
0
 def open_input(self, portname):
     if self.midiport:
         self.midiport.close()
     self.midiport = mido.open_ioport(portname, callback=self.recv_midi, autoreset=True)
     print "CONNECTED TO: %s" % self.midiport.name
    def __init__(self):
        self.port = mido.open_ioport('Launchpad Pro MIDI 1')

        buf_size = 10 * 10
        self.buf = [0 for i in range(buf_size)]
        self.back_buf = [0 for i in range(buf_size)]
Exemple #31
0
 def open_port(self):  # opens the input/output port selected by user
     print('Port in use is %s, channel' % self.inputs.port,
           (self.inputs.channel + 1))
     return mido.open_ioport(self.inputs.port)