コード例 #1
0
ファイル: main.py プロジェクト: marcinn/midicontrol
def main(midi_port_name, controller):
    port = rtmidi.RtMidiIn()

    tries = 0
    port_number = None

    while tries < 10:
        for x in range(port.getPortCount()):
            if port.getPortName(x).startswith(midi_port_name):
                port_number = x
                break
        if port_number is None:
            print("Waiting for device: %s" % midi_port_name)
            time.sleep(1)
            tries += 1
        else:
            break

    if port_number is None:
        raise ValueError(
                'Midi port "%s" was not found' % midi_port_name)

    port.openPort(port_number)
    port.setCallback(safe_handle(controller.handle_midi_event))

    print("Ctrl-C to abort")

    controller.run()
    port.closePort()
コード例 #2
0
ファイル: midi2ledstrip.py プロジェクト: davekch/diskolight
 def __init__(self, port, timeout=100):
     threading.Thread.__init__(self)
     self.device = rtmidi.RtMidiIn()
     self.port = port
     self.timeout = timeout
     self.queue = Queue()
     self.running = False
コード例 #3
0
ファイル: MidiNvim.py プロジェクト: ripxorip/midi.nvim
 def startMidi(self, args, range):
     self.ogBuffer = self.nvim.current.buffer
     # Start the status window
     self.nvim.command('split')
     self.nvim.command('wincmd j')
     self.nvim.command('e midi_status')
     self.nvim.current.window.height = 2
     self.nvim.command('setlocal buftype=nofile')
     self.nvim.command('setlocal filetype=midi_status')
     self.statusBufferNumber = self.nvim.current.buffer.number
     self.statusBuffer = self.nvim.current.buffer
     self.nvim.command('wincmd k')
     self.nvim.current.buffer = self.ogBuffer
     if self.midiin == None:
         self.midiin = rtmidi.RtMidiIn()
     if len(args) > 0:
         port = int(args[0])
     else:
         port = 0
     self.midiin.openPort(port)
     # Shall start a background thread
     self.threadShallRun = True
     self.midiThread = Thread(target=self.thread_midiHandler)
     self.midiThread.start()
     # Setup hander depending on the preset
     if self.mode == "programmer":
         self.handler = MidiNvimProgrammer(self.nvim, self.statusBuffer)
     #
     initialStatStr = "| Port \"" + self.midiin.getPortName(port)
     initialStatStr += "\" opened, waiting for MIDI..."
     self.statusBuffer[0] = initialStatStr
     # Always start in normal mode
     self.statusBuffer.append("| Mode: \"%s\" | Preset: \"%s\"" %
                              ("normal", self.mode))
コード例 #4
0
def main_inout_block():
    # don't set global var because we will output here
    # global midiout

    midiin = rtmidi.RtMidiIn()
    print 'INPUTS:'
    print_ports(midiin)
    midiin.openPort(1)  # KeyStation?

    midiout = rtmidi.RtMidiOut()
    print 'OUTPUTS:'
    print_ports(midiout)
    midiout.openPort(0)  # IAC?

    try:
        m = None
        while True:
            m = midiin.getMessage(250)
            if m:
                midiout.sendMessage(m)
                m = rtmidi.MidiMessage.aftertouchChange(
                    1, 1, m.getNoteNumber())
                print_message(m)
    except KeyboardInterrupt:
        pass

    midiin.closePort()
    print 'quit'
コード例 #5
0
ファイル: collector.py プロジェクト: Scott-Rubey/AudioSampler
 def addCollector(self, portName, start=False):
     if portName in self.collectors:
         return
     device = rtmidi.RtMidiIn()
     iPort = None
     for i in range(device.getPortCount()):
         if device.getPortName(i) == portName:
             iPort = i
             break
     if iPort is None:
         return
     if rtmidi.DEBUG:
         print('rtmidi.Collector.addCollector', portName, iPort)
     try:
         device.openPort(i)
     except:
         return
     collector = Collector(device, self._callback)
     collector.portName = portName
     self.collectors[portName] = {
         'collector': collector,
         'name': portName,
         'queue': []
     }
     if start:
         collector.start()
     return collector
コード例 #6
0
    def __init__(self,
                 controller_name='MPK Mini Mk II'
                 ):

        # settings
        self.rec_toggle_note = 4
        self.channel_toggle_note = 5
        self.controller_name = controller_name
        self.output_port_name = 'test_port'
        self.max_channel = 16

        # setup midi input
        self.inn = rtmidi.RtMidiIn()
        self.port_names = [self.inn.getPortName(i) for i in \
                range(self.inn.getPortCount())]
        self.input_port_idx = self.port_names.index(self.controller_name)
        self.inn.openPort(self.input_port_idx)

        # setup midi output
        self.out = rtmidi.RtMidiOut()
        self.out.openVirtualPort(self.output_port_name)

        # runtime
        self.recording = False
        self._channel = 1
        self.playback_t0 = time.time()
        self.recording_t0 = time.time()
        self.loop_duration = None
        self.buffers = []
        self.buffer_idxs = []
コード例 #7
0
def main():
    """Demo de control del S2 utilizando un controlador MIDI."""
    print("Creando puerta MIDI")
    midiIn = rtmidi.RtMidiIn()
    midiIn.openVirtualPort("S2 Control Port")

    print("Conectando con el Scribbler2")
    robot = Scribbler2("/dev/rfcomm2", 9600, 500)
    s2Motors = robot.getS2Motors()

    print("Conecte la puerta del Controlador Midi a la puerta virtual creada")
    while (True):
        cmd = None
        while (True):
            message = midiIn.getMessage()
            if (message == None):
                continue
            if (message.isNoteOn()):
                note = message.getNoteNumber()
                print(note)
                if (note == 48):
                    s2Motors.setMotors(100, -100)
                elif (note == 52):
                    s2Motors.setMotors(-100, 100)
                elif (note == 55):
                    s2Motors.setMotors(100, 100)
                elif (note == 59):
                    s2Motors.setMotors(-100, -100)
                elif (note == 83):
                    s2Motors.setMotorsOff()
    midiIn.close()
    robot.close()
コード例 #8
0
    def __init__(self, port=0):
        self.midiin = rtmidi.RtMidiIn()

        ports = range(self.midiin.getPortCount())

        if ports:
            self.midiin.openPort(port)
            print self.midiin.getPortName(port)
        else:
            print 'Error no input'
コード例 #9
0
def doScan():
    try:
        import rtmidi
    except ImportError:
        if once[0] == 0:
            messagebus.postMessage("/system/notifications/errors/","python-rtmidi is missing. Most MIDI related features will not work.")
            once[0]=1
        return


    m=rtmidi.RtMidiIn()
    torm =[]

    present =[(i,m.getPortName(i)) for i in range(m.getPortCount())]

    for i in allInputs:
        if not i in present:
            torm.append(i)
    for i in torm:
        del allInputs[i]


    for i in present:
        if not i in allInputs:
            try:
                m=rtmidi.RtMidiIn()
                m.openPort(i[0])
                def f(x,*a, d=i[1].replace(":",'_').replace("[",'').replace("]",'').replace(" ",'') ):
                    if isinstance(x,tuple):
                        try:
                            onMidiMessageTuple(x,d)
                        except:
                            print(traceback.format_exc())
                    else:
                        try:
                            onMidiMessage(x,d)
                        except:
                            print(traceback.format_exc())
                m.setCallback(f)
                allInputs[i]=(m,f)
            except:
                print("Can't use MIDI:"+str(i))
コード例 #10
0
ファイル: showMidiIn.py プロジェクト: Sgw32/tcp2midi
def refreshMidiPorts():
    global midiMsg
    midiMsg = MidiMessage()
    midiMsg.midiports = []
    if sys.version_info[1] == 8:
        midiMsg.midiobj = rtmidi.RtMidiIn()
        for i in range(midiMsg.midiobj.getPortCount()):
            midiMsg.midiports.append(midiMsg.midiobj.getPortName(i))
    else:
        midiMsg.midiobj = rtmidi.MidiIn()
        midiMsg.midiports = midiMsg.midiobj.get_ports()
コード例 #11
0
ファイル: collector.py プロジェクト: Scott-Rubey/AudioSampler
 def __init__(self, callback=None, autolist=True):
     threading.Thread.__init__(self)
     self._callback = callback and callback or self._callback
     self.collectors = {}
     if autolist:
         if rtmidi.DEBUG:
             print("rtmidi.CollectorBin.autolist = True")
         device = rtmidi.RtMidiIn()
         for i in range(device.getPortCount()):
             self.addCollector(device.getPortName(i))
     self.cond = threading.Condition()
     CollectorBin._bin.append(self)
     self.running = False
コード例 #12
0
def main_in():
    midiin = rtmidi.RtMidiIn()
    print_ports(midiin)

    midiin.setCallback(callback)
    midiin.openPort(1)  # KeyStation?

    try:
        while True:
            time.sleep(.1)
    except KeyboardInterrupt:
        pass
    midiin.closePort()
    print 'quit'
コード例 #13
0
ファイル: MidiNvim.py プロジェクト: ripxorip/midi.nvim
 def listMidiInputs(self, args, range):
     self.midiin = rtmidi.RtMidiIn()
     self.nvim.command('split Midi_Inputs')
     self.nvim.command('setlocal buftype=nofile')
     self.nvim.command('setlocal filetype=midi_inputs')
     portCount = int(self.midiin.getPortCount())
     self.nvim.current.line = "~ Listing " + str(
         portCount) + " MIDI port(s) ~"
     self.nvim.current.buffer.append("--------------------------")
     i = 0
     while (i < portCount):
         self.nvim.current.buffer.append("%d: %s" %
                                         (i, self.midiin.getPortName(i)))
         i += 1
コード例 #14
0
    def listRtmidi():
        try:
            import rtmidi
        except ImportError:
            if once[0] == 0:
                messagebus.postMessage(
                    "/system/notifications/errors/",
                    "python-rtmidi is missing. Most MIDI related features will not work."
                )
                once[0] = 1
            return []

        m = rtmidi.RtMidiIn()

        return [(m.getPortName(i)) for i in range(m.getPortCount())]
コード例 #15
0
def main_in_block():
    midiin = rtmidi.RtMidiIn()
    print_ports(midiin)

    midiin.openPort(1)  # KeyStation?

    try:
        m = None
        while True:
            m = midiin.getMessage(250)
            if m:
                print_message(m)
    except KeyboardInterrupt:
        pass
    midiin.closePort()
    print 'quit'
コード例 #16
0
def main_inout():
    global midiout
    midiin = rtmidi.RtMidiIn()
    print 'INPUTS:'
    print_ports(midiin)
    midiin.setCallback(callback)
    midiin.openPort(1)  # KeyStation?

    midiout = rtmidi.RtMidiOut()
    print 'OUTPUTS:'
    print_ports(midiout)
    midiout.openPort(0)  # IAC?

    while True:
        time.sleep(.1)
    midiin.closePort()
    print 'quit'
コード例 #17
0
    def run(self):
        print('Receiver thread started...')

        # Setup Receiver
        import rtmidi
        self.midiin = rtmidi.RtMidiIn()
        ports = range(self.midiin.getPortCount())
        if ports:
            for i in ports:
                print('Receiving from midi port "%s"' %
                      self.midiin.getPortName(i))
            self.midiin.openPort(len(ports) - 1)
            while self.running:
                message = self.midiin.getMessage(250)  # some timeout in ms
                if message:
                    print(message, '(received)')
        else:
            print('NO MIDI INPUT PORTS!')
コード例 #18
0
def _create_midi_connection() -> Optional[RtMidiIn]:
    midi_in: RtMidiIn = rtmidi.RtMidiIn()

    print("Looking for MIDI input ports...")
    ports = range(midi_in.getPortCount())
    if ports:
        print(f'{len(ports)} MIDI ports found!')
        for index, item in enumerate(ports):
            print(f'{index}) {midi_in.getPortName(item)}')

        # TODO: We can add input/prompt here to allow for picking which one to connect to if more than 1.
        print("Opening port 0!")
        midi_in.openPort(0)

        return midi_in
    else:
        print('NO MIDI INPUT PORTS!')

    return None
コード例 #19
0
ファイル: midi.py プロジェクト: bergamote/micronux
def interface(port, action, syx=False):
    ''' Interface for midi send/receive sysex

        action 'receive'    saves file at
                            'receive_cache'
        action 'send'       send syx
        return True when done
    '''
    port = find_midi_port(port)
    if port:
        if action == 'receive':
            # wait in number of seconds
            # and/or midi messages
            waiting = 10
            received = False
            md = rtmidi.RtMidiIn()
            md.openPort(port)
            md.ignoreTypes(False, True, True)
            while waiting and not received:
                msg = md.getMessage(1000)
                if msg and validate_syx(msg):
                    save_syx(msg)
                    received = True
                    break
                waiting -= 1
            md.closePort()
            return received

        elif action == 'send':
            if not syx:
                return False
            else:
                md = rtmidi.RtMidiOut()
                md.openPort(port)
                msg = rtmidi.MidiMessage(syx)
                if validate_syx(msg):
                    md.sendMessage(msg)
                    return True
    else:
        print('MIDI port not valid')
        return False
コード例 #20
0
ファイル: core.py プロジェクト: afcarl/midi2sc
def main(options=None, callback=None):
    if options is None:
        options, args = _parse_options()

    if not isinstance(options, dict):
        # options doesn't have a very nice interface at this point; it
        # has ``None`` for all values not set when using optparse, but
        # it may missing values instead in case of manual call of
        # ``main()``.
        options = dict(options.__dict__)

    set_verbosity(options['verbose'])
    server = connect(
        options.get('host') or 'localhost',
        options.get('port') and int(options['port']) or 57110)

    midi = rtmidi.RtMidiIn()
    midi_port = options.get('midi_port')
    if midi_port is None:
        midi_port = ask_for_port(midi)
    midi_port = int(midi_port)

    from midi2sc import configure
    handlers = configure.read(options.get('filename') or 'midi2sc.ini')
    midi_in = MidiIn(midi, midi_port, handlers=handlers)
    midi_in.start()

    if callback is None:
        from midi2sc import gui
        gui.start()

        scope = dict(globals())
        scope.update(locals())
        code.interact(local=scope)
    else:
        callback(locals())
コード例 #21
0
ファイル: midi_stuff.py プロジェクト: nlml/dreamz
def get_rtmidi_obj(port):
    rtmidi_obj = rtmidi.RtMidiIn()
    rtmidi_obj.openPort(port)
    return rtmidi_obj
コード例 #22
0
ファイル: main.py プロジェクト: bakowroc/midi-controller
def print_message(value):
    note = value.getNoteNumber()

    if value.isNoteOn():
        if note not in active_sounds:
            midi_msg = MIDIMessage(value, p)
            active_sounds[note] = midi_msg
            midi_msg.start()

    elif value.isNoteOff():
        try:
            active_sounds[note].on_note_off()
            del active_sounds[value.getNoteNumber()]
        except KeyError:
            pass


if __name__ == "__main__":
    if EXAMINE:
        print('Examine')
        plot(clean(440))
    else:
        MIDIDevice = rtmidi.RtMidiIn()

        MIDIDevice.openPort(1)
        while True:
            message = MIDIDevice.getMessage(100)
            if message:
                print_message(message)

コード例 #23
0
		self.portName = device.getPortName(port)
		self.device = device
		self.quit = False

	def run(self):
		self.device.openPort(self.port)
		self.device.ignoreTypes(True, False, True)
		while True:
			if self.quit:
				return
			msg = self.device.getMessage()
			if msg:
				#print([hex(i) for i in msg.getRawData()])
				#print_message(msg, self.portName)
				send_msg([i for i in msg.getRawData()])

dev = rtmidi.RtMidiIn()
collectors = []
for i in range(dev.getPortCount()):
	device = rtmidi.RtMidiIn()
	print('OPENING',dev.getPortName(i))
	collector = Collector(device, i)
	collector.start()
	collectors.append(collector)


print('HIT ENTER TO EXIT')
sys.stdin.read(1)
for c in collectors:
	c.quit = True
コード例 #24
0
            if self.quit:
                return
            # Read any available MIDI message
            midiMessage = self.midiDevice.getMessage()
            if midiMessage and midiMessage.isController():
                controllerNumber = midiMessage.getControllerNumber()
                controllerValue = midiMessage.getControllerValue()
                if debug:
                    print(controllerNumber, controllerValue)
                # Map MIDI message to HAL pin
                self.hal[str(self.port) + '.controller.' +
                         str(controllerNumber) + '.out'] = controllerValue


try:
    midiIn = rtmidi.RtMidiIn()
    collectors = []

    # Go through all MIDi devices
    for port in range(midiIn.getPortCount()):
        midiDevice = rtmidi.RtMidiIn()
        if debug:
            print(midiIn.getPortName(port))

        collector = Collector(midiDevice, port, halMidi)
        collector.start()
        collectors.append(collector)

        # Add HAL pins for all possible MIDI controllers on each device
        # (I don't see how I would identify what controllers that actually are present on a device)
        for controller in range(0, 127):
コード例 #25
0
ファイル: Input.py プロジェクト: Gamer125/fofix
ports = None
midi = []
midiin = None
portCount = 0
try:
    import rtmidi
    haveMidi = True
except ImportError:
    haveMidi = False

#haveMidi = False  #this line disables the rtmidi module for computers with 0 midi ports...has to be this way for now to avoid crashes.

if haveMidi:
    try:
        midiin = rtmidi.RtMidiIn()
        portCount = midiin.getPortCount()
        #Log.debug("MIDI port count = " + str(portCount) )
        if portCount > 0:
            ports = range(portCount)
            for x in ports:
                midi.append(rtmidi.RtMidiIn())
    except Exception, e:
        Log.error(str(e))
        ports = None

from Task import Task
from Player import Controls

import Config  #MFH
コード例 #26
0
 def __init__(self, portName = 'MPD218'):
     super().__init__()
     self.midiin = rtmidi.RtMidiIn()
     self.portName = portName
コード例 #27
0
import rtmidi

midiin = rtmidi.RtMidiIn()

def print_message(midi):
    if midi.isNoteOn():
        print('ON: ', midi.getMidiNoteName(midi.getNoteNumber()), midi.getVelocity())
    elif midi.isNoteOff():
        print('OFF:', midi.getMidiNoteName(midi.getNoteNumber()))
    elif midi.isController():
        print('CONTROLLER', midi.getControllerNumber(), midi.getControllerValue())

ports = range(midiin.getPortCount())
if ports:
    for i in ports:
        print(midiin.getPortName(i))
    print("Opening port 0!") 
    midiin.openPort(0)
    while True:
        m = midiin.getMessage(250) # some timeout in ms
        if m:
            print_message(m)
else:
    print('NO MIDI INPUT PORTS!')
コード例 #28
0
def main(*args):

    param = fetchParameter(*args)
    t = Terminal()

    if param['min_note'] != None:
        min_notes = param['min_note']
    else:
        min_notes = 40

    midiIn = rtmidi.RtMidiIn()

    port_num = midiIn.getPortCount()
    ports = range(port_num)

    if not ports:
        print("No open port found, exiting...")
        exit()

    if param['port'] != None:
        print("Using port " + t.bold + str(param['port']) + t.normal)
        port = param['port']

        if port > port_num or port < 0:
            print("\n" + t.bold + t.red + "[X]"  + t.normal + "Invalid port selected\n")
            exit()

    else:
        #Start the getPortNumber routine
        while True:
            devices = {}
            
            port_num = midiIn.getPortCount()
            ports = range(port_num)
            
            for i in ports:
                devices[i] = str(midiIn.getPortName(i))

            port = getPortNumber(port_num, devices, t)

            if port != "REFRESH":
                break



    print("\nOpening port: " + t.bold + str(port) + t.normal)
    
    midiIn.openPort(port)


    buffer = []

    fetcher = NoteFetcher(midiIn, buffer)
    fetcher.start()     #Start the fetcher in another thread

    print t.underline + "Continue to play notes until the entropy bar is full\n" + t.no_underline

    bar = ChargingBar('Entropy', suffix='%(percent)d%%', max=min_notes)
    prev_dim = 0


    while len(buffer) < min_notes:
        if len(buffer) != prev_dim:
            for i in range(len(buffer)-prev_dim):
                bar.next()
            prev_dim = len(buffer)
        time.sleep(0.01)


    bar.finish()

    cmd = ""
    while cmd != "stop":
        cmd = str(raw_input("\nWrite \"" + t.bold + t.red + "stop" + t.normal + "\" to generate the password: "******"\n" + t.underline + "Final array" + t.no_underline + ": " + binascii.hexlify(byte_buffer))

    note_list = ""
    for note in buffer:
        note_list += note.getMidiNoteName(note.getNoteNumber()) + " "
    print("\nNotes:\n\t" + note_list)


    print("\n\n")

    #Set the Salt
    if param['salt'] != None:
        salt = param['salt']
    else:
        salt = str(raw_input("Insert a salt: "))

    #Select the key derivation function
    if param['func'] == None:
        while True:
            print("\nSelect the algorithm to use for the key derivation")
            print("\n\t" + t.yellow + "(" + t.normal + t.bold + "0" + t.normal + t.yellow + ")" + t.normal + " - pbkdf2 (default)\n\t" + t.yellow + "(" + t.normal + t.bold + "1" + t.normal + t.yellow + ")" + t.normal + "- scrypt (unimplemented)")
            key_func = int(raw_input("Choice : "))
            if key_func == 0:
                param['func'] = "pbkdf2"
                break
            elif key_func == 1:
                #param['func'] = "scrypt"
                #break
                print("Unimplemented :-(\n")
            else:
                print("Please choose a valid function\n")
                continue


    if param['func'] == "pbkdf2":
        key = hashlib.pbkdf2_hmac('sha512', byte_buffer, salt, param['round'])
    elif param['func'] == "scrypt":
        #n = int(raw_input("Insert 'n' parameter: "))
        #r = int(raw_input("Insert 'r' parameter: "))
        #p = int(raw_input("Insert 'p' parameter: "))
        #key_len = int(raw_input("Insert key length: "))
        #key = hashlib.scrypt(buffer, salt, n, r, p, dklen=key_len)
        print("Unimplemented")

    hex_key = binascii.hexlify(key)

    print("\n\nKey is : \t| " + t.bold + str(hex_key) + t.normal + " |\n\n")
コード例 #29
0
from binascii import hexlify, unhexlify
import traceback
import json as JSON
import re


def ipcSend(name, data):
    print(JSON.dumps([name, data]))
    stdout.flush()


try:
    import rtmidi
    API = rtmidi.RtMidiIn.UNIX_JACK if 'jack' in argv else rtmidi.RtMidiIn.UNSPECIFIED
    JACK = API == rtmidi.RtMidiIn.UNIX_JACK
    in_dev = rtmidi.RtMidiIn(API, 'MIDI->OSC probe')
    out_dev = rtmidi.RtMidiOut(API, 'OSC->MIDI probe')
except:
    ipcSend(
        'error',
        'pyrtmidi not found (or wrong version)\nRunning with python version %s'
        % version)
    exit()

if version_info.major == 3:
    raw_input = input

debug = False
if 'debug' in argv:
    debug = True
コード例 #30
0
from binascii import hexlify, unhexlify
import traceback
import json as JSON
import re


def ipcSend(name, data):
    print(JSON.dumps([name, data]))
    stdout.flush()


try:
    import rtmidi
    API = rtmidi.RtMidiIn.UNIX_JACK if 'jack' in argv else rtmidi.RtMidiIn.UNSPECIFIED
    JACK = API == rtmidi.RtMidiIn.UNIX_JACK
    in_dev = rtmidi.RtMidiIn(API, 'Midi->OSC probe')
    out_dev = rtmidi.RtMidiOut(API, 'OSC->Midi probe')
except:
    ipcSend('error', 'pyrtmidi not found (or wrong version)')

if version_info.major == 3:
    raw_input = input

debug = False
if 'debug' in argv:
    debug = True


def list():

    message = []