Ejemplo n.º 1
0
 def __init__(self, turtle, devname, cb=False):
     self.turtle = turtle
     if cb:
         self.midi_in = mido.open_input(devname, callback=self.midi_callback)
     else:
         self.midi_in = mido.open_input(devname)
     self.midi_out = mido.open_output(devname)
     self.rgb = True
     self.size = 1
     self._update_rgb_indicator()
Ejemplo n.º 2
0
    def eloop(self, render_callback):
        cb = callback_factory(render_callback)
        try:
            midin = mido.open_input(
                name=self.port, virtual=True, callback=cb)
        except IOError:  # couldn't create virtual port
            midin = mido.open_input(name=self.port, callback=cb)
        except:
            raise complain.ComplainToUser("Could not find a valid MIDI input")

        midin.close()
Ejemplo n.º 3
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad S', callback=True)
            except IOError:
                input = mido.open_input('Launchpad S MIDI 1', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad S')
            except IOError:
                output = mido.open_output('Launchpad S MIDI 1')

        super(LaunchpadS, self).__init__(input, output)
Ejemplo n.º 4
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad Mini', callback=True)
            except IOError:
                input = mido.open_input('Launchpad Mini MIDI 1', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad Mini')
            except IOError:
                output = mido.open_output('Launchpad Mini MIDI 1')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(Launchpad, self).__init__(input, output)
Ejemplo n.º 5
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad Pro Standalone Port', callback=True)
            except IOError:
                input = mido.open_input('Launchpad Pro MIDI 2', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad Pro Standalone Port')
            except IOError:
                output = mido.open_output('Launchpad Pro MIDI 2')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(LaunchpadPro, self).__init__(input, output)
Ejemplo n.º 6
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
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
    def wait(self):
        with mido.open_input(self.device_name) as incoming:
            for msg in incoming:
                if msg.type == 'note_on' and msg.note in self.notes:
                    return (msg.note, msg.velocity)

        return False
Ejemplo n.º 9
0
def Run():
    global mt
    global nvalue
    global pnvalue
    
    with mido.open_output(autoreset = True) as o:
        with mido.open_input() as i:
            while True:
                for message in i:
                    if message.type == 'control_change':## and not message.control == 13:
                        print("in : " + str(message))
                        Translate(message,o)
                        
                    if 'note' in mt:
                        if not pnvalue == nvalue:
                            mo = mido.Message(mt,note = nvalue, velocity = 100)
                            print("out : " + str(mo))
                            o.send(mo)
                            pnvalue = nvalue
                        ##microgranny tends not to respond to off or time, or anything it doesn't like
                        if 'off'in mt:
                            mt = ''
                            o.send(mido.Message('note_off',note = pnvalue))
                            o.send(mido.Message('note_off',note=nvalue))
                            print("out : note_off")
                            o.reset()
                            o.panic()
                            ManualPanic(o)
Ejemplo n.º 10
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!")
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()
Ejemplo n.º 12
0
 def start(self):
     if self.midi_inport:
         with mido.open_input(self.midi_inport) as input:
             for message in input:
                 if message.type == 'control_change':
                     if message.channel == self.channel:
                         if message.control == self.bcontrolnum:
                             self.beat.set_control_beat(message.value)
                         elif message.control == self.tcontrolnum:
                             self.bpm.set_control_bpm(message.value)
                         elif message.control == self.rcontrolnum:
                             self.rms.set_control_rms(message.value)
                         elif message.control == self.pcontrolnum:
                             self.pitch.set_control_pitch(message.value)
                 elif message.type == 'sysex':
                     prefix = list(message.data[0:len(self.sysex_prefix)])
                     command = message.data[len(self.sysex_prefix)]
                     data = list(message.data[len(self.sysex_prefix) + 1:])
                     if cmp(prefix, self.sysex_prefix) == 0:
                         if command == self.bsysexnum:
                             self.beat.set_sysex_beat(data)
                         elif command == self.tsysexnum:
                             self.bpm.set_sysex_bpm_two_bytes(data)
                         elif command == self.rsysexnum:
                             self.rms.set_sysex_rms(data)
                         elif command == self.fsysexnum:
                             self.frequencies.set_sysex_frequencies(data)
                         elif command == self.psysexnum:
                             self.pitch.set_sysex_pitch(data)
                 elif message.channel == self.channel:
                     if message.type == 'note_on':
                         self.pitch.set_note_pitch(message.note)
                     elif message.type == 'note_off':
                         self.pitch.set_last_note_pitch(message.note)
Ejemplo n.º 13
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"
Ejemplo n.º 14
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.')
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
  def __init__(self, input_midi_port, output_midi_port, texture_type,
               passthrough=True):
    self._texture_type = texture_type
    self._passthrough = passthrough
    # 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 string-formatted mido.Messages to a condition
    # variable that will be notified when a matching messsage is received,
    # ignoring the time field.
    self._signals = {}
    # 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.
    self._inport = (
        input_midi_port if isinstance(input_midi_port, mido.ports.BaseInput)
        else mido.open_input(
            input_midi_port,
            virtual=input_midi_port not in get_available_input_ports()))
    self._outport = (
        output_midi_port if isinstance(output_midi_port, mido.ports.BaseOutput)
        else mido.open_output(
            output_midi_port,
            virtual=output_midi_port not in get_available_output_ports()))

    # Start processing incoming messages.
    self._inport.callback = self._timestamp_and_handle_message
Ejemplo n.º 17
0
    def __init__(self, port_name, trace=False):
        """
        Construct new MIDIReceiver object.
        DO NOT instinate directly, use get_midi_receiver function instead.

        ARGS:
          port_name - String.
                      For a list of available ports execute the mido-ports
                      script on the command line. 
        """
        self._dispatch_table = {"note_on" : {},
                                "note_off" : {},
                                "program_change" : {},
                                "aftertouch" : {},
                                "control_change" : {},
                                "pitchwheel" : {},
                                "polytouch" : {},
                                "sysex" : {},
                                "quarter_frame" : {},
                                "songpos" : {},
                                "song_select" : {},
                                "tune_request" : {},
                                "clock" : {},
                                "start" : {},
                                "continue" : {},
                                "stop" : {},
                                "reset" : {},
                                "active_sensing" : {}}
        self._port_name = port_name
        self._port = mido.open_input(self._port_name)
        self._thread = None
        self._active = False
        self.enable_trace(trace)
Ejemplo n.º 18
0
    def capture(self):
        self.capturing = False
        self.final_tick = False
        # Start clocks at -1 to account for Circuit's leading clock message after start
        self.clocks = [-1, -1, -1]
        self.total_ticks = 0

        output_dir = os.path.dirname(self.output)
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        mido.set_backend('mido.backends.rtmidi')

        with mido.MidiFile(type=1, ticks_per_beat=TICKS_PER_BEAT) as mid:
            # Create tracks
            self.tempo_map_track = mid.add_track(name=SONG_NAME)
            self.tracks = [mid.add_track(name="Synth 1"),
                mid.add_track(name="Synth 2"),
                mid.add_track(name="Drums")]

            # Set synth instruments
            self.tracks[CHANNEL_SYNTH1].append(mido.Message('program_change', program=PROGRAM_SYNTH1))
            self.tracks[CHANNEL_SYNTH2].append(mido.Message('program_change', program=PROGRAM_SYNTH2))

            with mido.open_input(self.input) as port:
                print("Push 'Play' to start capture.")
                for msg in port:
                    if not self.process_message(msg):
                        break

            self.capturing = False
            self.write_tempo_map()
            mid.save(self.output)

        print("All done!")
Ejemplo n.º 19
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input(
                    'Ableton Push User Port',
                    callback=True)
            except IOError:
                input = mido.open_input('Ableton Push MIDI 2', callback=True)
        if output is None:
            try:
                output = mido.open_output('Ableton Push User Port')
            except IOError:
                output = mido.open_output('Ableton Push MIDI 2')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(Push, self).__init__(input, output)
Ejemplo n.º 20
0
 def __init__(self, input_midi_port, output_midi_port):
   self._inport = mido.open_input(input_midi_port)
   self._outport = mido.open_output(output_midi_port)
   # This lock is used by the serialized decorator.
   self._lock = threading.RLock()
   self._control_cvs = dict()
   self._player = None
   self._capture_start_time = None
   self._sequence_start_time = None
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
def monitor_midi():
    inny = mido.open_input()
    while True:
        msg = inny.receive()
        msg.time = get_usec_timestamp()
        msg = str(msg)
        print msg
        msg += "\n" 
        midi_file.write(str(msg))
Ejemplo n.º 23
0
    def __init__(self, daemonize=False, buflen=80):
        self.scrollwheel = 0
        self.buflen = buflen
        self.lines = collections.deque([''] * self.buflen)
        self.lock = threading.Lock()

        try:
            # Ports on MAC OSX
            self.output = mido.open_output('Ableton Push User Port')
            self.input = mido.open_input('Ableton Push User Port',
                                         callback=self.callback)
        except IOError:
            # Ports on Arch Linux
            self.output = mido.open_output('Ableton Push MIDI 2')
            self.input = mido.open_input('Ableton Push MIDI 2',
                                         callback=self.callback)

        while True:
            line = sys.stdin.readline()
            if not line:
                # EOF from STDIN
                break

            # We need to use mutex because concurrent reads and writes on
            # dequeue (scrolling while there is new text coming in from stdin)
            # will issue warnings.
            self.lock.acquire()
            self.lines.append(line)
            self.lines.popleft()
            self.lock.release()
            self.redraw()

        # Do not quit process if running daemonized
        # This enables scrolling for one-show piping to Push
        #
        # e.g. ping www.google.de | pushcat is scrollable as long as ping runs
        # ls | pushcat is not scrollable as ls immediately terminates
        # ls | pushcat -d enables scrolling
        if daemonize:
            while True:
                try:
                    time.sleep(0.1)
                except KeyboardInterrupt:
                    sys.exit(0)
Ejemplo n.º 24
0
    def wait(self):
        try:
            with mido.open_input(self.device_name) as incoming:
                for msg in incoming:
                    if msg.type == 'note_on' and msg.note in self.notes:
                        return (msg.note, msg.velocity)
        except IOError:
            dsp.log('Could not arm MIDI device %s' % self.device_name)

        return (None, None)
Ejemplo n.º 25
0
Archivo: mt2.py Proyecto: 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()
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
  def __init__(self, input_midi_ports, output_midi_ports, texture_type,
               passthrough=True, playback_channel=0, playback_offset=0.0):
    self._texture_type = texture_type
    self._passthrough = passthrough
    self._playback_channel = playback_channel
    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 = collections.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, mido.ports.BaseInput):
          inport = port
        else:
          virtual = port not in get_available_input_ports()
          if virtual:
            tf.logging.info(
                "Opening '%s' as a virtual MIDI port for input.", port)
          inport = mido.open_input(port, virtual=virtual)
        # Start processing incoming messages.
        inport.callback = self._timestamp_and_handle_message
    else:
      tf.logging.warn('No input port specified. Capture disabled.')
      self._inport = None

    outports = []
    for port in output_midi_ports:
      if isinstance(port, mido.ports.BaseInput):
        outports.append(port)
      else:
        virtual = port not in get_available_output_ports()
        if virtual:
          tf.logging.info(
              "Opening '%s' as a virtual MIDI port for output.", port)
        outports.append(mido.open_output(port, virtual=virtual))
    self._outport = mido.ports.MultiPort(outports)
Ejemplo n.º 28
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
Ejemplo n.º 29
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
Ejemplo n.º 30
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))
Ejemplo n.º 31
0

def lightsOff():
    print("Sending cancel")
    msg = mido.Message('sysex', data=[0, 74, 79, 72, 65, 83, 127])
    outport.send(msg)


def lightsOnOne(light):
    lightsOff()
    msg = mido.Message('program_change', channel=11, program=light)
    outport.send(msg)


pro = 0
with mido.open_input(organ) as inport:
    print(inport)
    for msg in inport:
        print(msg)
        if msg.type == 'note_on' and msg.note == 36 and msg.velocity != 0:
            # See if something is already playing and kill it
            if pro != 0:
                os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
                outport.reset()
                pro = 0

            lightsOn(len(files))
            # Wait for messages to pass
            time.sleep(0.2)  # Wait for messages to arrive
            for msg in inport.iter_pending():
                print(msg)
Ejemplo n.º 32
0
                    elif time.time() >= time_pedal_is_down + 2.50:
                        print(
                            'was held! adding note_queue to chord_progression.'
                        )
                        chord_progression.insert(0, note_queue)
                        note_queue = []
                        return
                    print('computer should not record.')
                    computer_should_record = False
                    time_since_pedal_released = time.time()
                else:
                    pass


input_name = mido.get_input_names()[0]
input_port = mido.open_input(input_name, callback=handle_message)

output_name = mido.get_output_names()[0]
output_port = mido.open_output(output_name)


def main():
    global note_queue
    global input_port
    global output_port
    global computer_should_record
    global init_time
    global last_time

    while not init:
        time.sleep(0.1)
Ejemplo n.º 33
0
import board
import busio

i2c_1 = busio.I2C(board.SCL, board.SDA)
#i2c_2 = busio.I2C(24, 23)

dac_PITCH = adafruit_mcp4725.MCP4725(i2c_1, address=0x60)
dac_HOLD = adafruit_mcp4725.MCP4725(i2c_1, address=0x61)
#dac_MOD = adafruit_mcp4725.MCP4725(i2c_2, address= 0x60)
#dac_TRIG = adafruit_mcp4725.MCP4725(i2c_2, address= 0x61)

from midi_handler import *
from port_manager import *

p = PortManager()
m = MidiHandler()

try:
    while True:
        if not p.is_scanning:
            with mido.open_input(p.input_name) as port:
                while not port.closed:
                    for msg in port.iter_pending():
                        m.input_signal(msg)
                    if p.is_scanning:
                        port.close()
                    dac_PITCH.normalized_value = m.PITCH_V
except KeyboardInterrupt:
    GPIO.cleanup()
    print("\nExiting..")
Ejemplo n.º 34
0
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():
        msg = inport.receive()
        if msg.type == "control_change":
            if msg.control in cc_cmds:
Ejemplo n.º 35
0
# this determines how much debugging information gets printed
debug = patch.getint('general', 'debug')

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

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

try:
    outputport = mido.open_output(mididevice)
    if debug > 0:
        print("Connected to MIDI output")
except:
    print("Error: cannot connect to MIDI output")
    exit()

try:
Ejemplo n.º 36
0
#plt.ylim(0,5)
#plt.xlim(20,109)
#plt.show(block=False)

def update_plot(msg, time):
    if msg.type == 'note_on':
        print(msg)
        if msg.velocity == 0:
            return
        x.append(time)
        y.append(msg.note)
        z.append(max(1, msg.velocity-40)*3)
        sc.set_offsets(numpy.c_[y,x])
        sc.set_sizes(z)
        fig.canvas.draw_idle()
        plt.ylim(time - 15, time+1)
        plt.pause(0.01)

def print_diff(msg, time):
        x.append(time)
        print(x[-1] - x[-2])
        #y.append(msg.note)
        #z.append(max(1, msg.velocity-40)*3)


with mido.open_input(portname) as inport:
    for msg in inport:
        if msg.type == 'note_on' and msg.velocity !=0:
            print_diff(msg, time.time() - start)
            #update_plot(msg, time.time() - start)
Ejemplo n.º 37
0
class pyPOD:

    midi_channel = 1
    msg_bytes = []
    manufacturer_id = ""
    pod_version = ""
    product_family = ""
    product_family_member = ""
    inport = mido.open_input()
    outport = mido.open_output()
    logger = logging.getLogger("pyPod")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s -  %(name)s -  %(levelname)s - %(funcName)s - %(message)s'
    )
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    def __init__(self, **kwargs):
        if "loglevel" in kwargs.keys():
            self.set_loglevel(kwargs["loglevel"])
        self.logger.debug('init pyPOD')
        self.inport.callback = self.monitor_input
        self.load_config()

    def set_loglevel(self, loglevel):
        self.ch.setLevel(loglevel)

    def load_config(self):
        self.logger.debug('looking for config')
        rcfile = "/.pypodrc"
        homerc = os.environ['HOME'] + rcfile
        pwdrc = os.environ['PWD'] + rcfile
        rcfile = ""
        config = ""
        if os.path.isfile(homerc):
            self.logger.debug(f"found {homerc}")
            rcfile = homerc
        elif os.path.isfile(pwdrc):
            self.logger.debug(f"found {pwdrc}")
            rcfile = pwdrc
        else:
            self.logger.info("no config file found")
        if rcfile != "":
            with open(rcfile, "r") as fd:
                config = json.load(fd)
            if 'MIDI_IN' in config.keys():
                self.logger.debug(f"MIDI_IN: {config['MIDI_IN']}")
                self.connect_input(config['MIDI_IN'])
            if 'MIDI_OUT' in config.keys():
                self.logger.debug(f"MIDI_OUT: {config['MIDI_OUT']}")
                self.connect_output(config['MIDI_OUT'])
            if 'MIDI_CHAN' in config.keys():
                self.logger.debug(f"MIDI_CHAN: {config['MIDI_CHAN']}")
                self.midi_channel = int(config['MIDI_CHAN'])

    def connect_input(self, midi_in):
        self.logger.info(f"connecting to input {midi_in}")
        try:
            self.inport = mido.open_input(midi_in)
        except OSError:
            # open default instead:
            self.logger.warning("error opening input, using default")
            self.inport = mido.open_input()
        self.inport.callback = self.monitor_input

    def connect_output(self, midi_out):
        self.logger.info(f"connecting to output {midi_out}")
        try:
            self.outport = mido.open_output(midi_out)
        except OSError:
            self.logger.warning("error opening output, using default")
            self.outport = mido.open_output()

    def show_midiports(self):
        # a little helper-function for the command line
        # run this script with the -o parameter --show-midiports
        # and put the name of the connected midi-port in the config
        inports = mido.get_input_names()
        outports = mido.get_output_names()
        return inports, outports

    def denib(self, highnibble, lownibble):
        # from https://medias.audiofanzine.com/files/lin020-477344.pdf:
        #POD sends and receives Program and Global dump data in High-Low Nibbilized format.
        #ONE POD BYTE (8 bits):0: A7 A6 A5 A4 A3 A2 A1 A0
        #TRANSMITTED and RECEIVED AS:
        #0: 00 00 00 00 A7 A6 A5 A4
        #1: 00 00 00 00 A3 A2 A1 A0
        ret_byte = highnibble << 4
        ret_byte = ret_byte | lownibble
        return ret_byte

    def nib(self, in_byte):
        # reverse function of denib, for creating data to be sent to the pod
        highnibble = in_byte >> 4
        lownibble = in_byte & 0b1111
        return highnibble, lownibble

    def dump_editbuffer(self):
        self.logger.info("dumping edit bufer")
        msg = mido.Message('sysex', data=[0x00, 0x01, 0x0c, 0x01, 0x00, 0x01])
        self.outport.send(msg)

    def dump_program(self, program):
        # dump a single program from the pod:
        self.logger.info(f"Dumping program {program} from pod")
        msg = mido.Message('sysex',
                           data=[
                               0x00, 0x01, 0x0c, 0x01, 0x00, 0x00,
                               line6.PROGRAMS.index(program)
                           ])
        self.outport.send(msg)

    def upload_editbuffer(self):
        self.logger.info("Upload to edit buffer")
        msg = mido.Message('sysex', data=[0x00, 0x01, 0x0c, 0x01, 0x01, 0x01])
        message = mido.Message('sysex')
        for byte in self.msg_bytes:
            message.data += self.nib(byte)
        msg.data += message.data[1:]
        #self.logger.debug(f"message length: {len(message.data)}")
        #self.logger.debug(f"msg.data: {msg.data}")
        #self.logger.debug(f"total length: {len(msg.data)}")
        self.outport.send(msg)

    def upload_program(self, program):
        self.logger.info(f"Uploading to program {program}")
        # uploads a single program to the pod:
        msg = mido.Message('sysex',
                           data=[
                               0x00, 0x01, 0x0c, 0x01, 0x01, 0x00,
                               line6.PROGRAMS.index(program)
                           ])
        # somehow we have to cut the first element, I have no idea why
        # found out because uploading did not work and compared data-dumps
        # from jsynthlib with mine and found out I transmitted one extra byte...
        message = mido.Message('sysex')
        for byte in self.msg_bytes:
            message.data += self.nib(byte)
        msg.data += message.data[1:]
        self.logger.debug(f"message length: {len(message.data)}")
        self.logger.debug(f"msg.data: {msg.data}")
        self.logger.debug(f"total length: {len(msg.data)}")
        self.outport.send(msg)

    def udq(self):
        msg = mido.Message('sysex', data=[0x7e, self.midi_channel, 0x06, 0x01])
        self.outport.send(msg)

    def parse_progdump(self, message):
        self.msg_bytes = []
        offset = 1
        if len(message) == 152:
            offset = 7  # data starts after byte 9
        for x in range(0, 72):
            self.msg_bytes.append(
                self.denib(message.bytes()[x * 2 + offset],
                           message.bytes()[x * 2 + offset + 1]))
        return

    def get_program_name(self):
        return "".join(map(chr, self.msg_bytes[56:]))

    def monitor_input(self, message):
        # a single program dump is 152 bytes long (9 bytes header, 142 bytes data, &xF7 is the last byte)
        if message.type == 'sysex' and len(message.bytes()) == 152:
            self.logger.info(f"Received sysex (program dump)")
            self.parse_progdump(message)
        elif message.type == 'sysex' and len(message.bytes()) == 17:
            self.pod_version = "".join(
                [chr(x) for x in message.bytes()[12:16]])
            self.manufacturer_id = "{:02X} {:02X} {:02X}".format(
                message.bytes()[5],
                message.bytes()[6],
                message.bytes()[7])
            self.product_family = "{:02X}{:02X}".format(
                message.bytes()[9],
                message.bytes()[8])
            self.product_family_member = "{:02X}{:02X}".format(
                message.bytes()[11],
                message.bytes()[10])
            self.logger.info("Received sysex (device info)")
        elif message.type == 'sysex' and len(message.bytes()) == 151:
            # the editbuffer-dump is one byte shorter than a regular program dump
            dummymsg = mido.Message('sysex', data=[0])
            message.data = dummymsg.data + message.data
            self.parse_progdump(message)
            self.logger.info("Received sysex (edit buffer)")
        elif message.type == 'program_change' and len(message.bytes()) == 2:
            prog = "Edit Buffer" if message.bytes(
            )[1] == 0 else line6.PROGRAMS[message.bytes()[1] - 1]
            self.logger.info(f"Received program_change message: {prog}")
        else:
            self.logger.warning(
                f"Unknown message type {message.type}: {message.bytes()} ({len(message.bytes())}) bytes:"
            )

    def get_info(self):
        # get infos about the device:
        self.udq()
        time.sleep(1)
        print("POD Version: {}".format(self.pod_version))
        print("Manufacturer ID: {}".format(self.manufacturer_id))
        print("Product Family ID: {}".format(self.product_family))
        print("Product Family Member: {}".format(self.product_family_member))

    def dump_raw(self, **kwargs):
        if 'filename' in kwargs:
            # if filename is given, dump to syx file:
            # update: create sysex-message so we don't have to manually add the
            # first and last byte
            message = []
            for m in self.msg_bytes[:]:
                h, l = self.nib(m)
                message.append(h)
                message.append(l)
            msg = mido.Message('sysex', data=message)
            mido.write_syx_file(kwargs['filename'], (msg, ))
        else:
            print(*self.msg_bytes)

    def dump_hex(self):
        # print values as hex
        hexbytes = []
        for b in self.msg_bytes[:]:
            hexbytes.append("{:02X}".format(b))
        print(*hexbytes)

    def load_syx(self, filename):
        messages = mido.read_syx_file(filename)
        message = mido.Message('sysex', data=messages[0].data)
        self.parse_progdump(message)

    def change_name(self, new_name):
        """changes the name string of a patch"""
        if len(new_name) > 16:
            # the maximum length is 16 characters
            new_name = new_name[:16]
        if len(new_name) < 16:
            # fill it up with spaces:
            new_name = new_name + (" " * (16 - len(new_name)))
        # create a list of ascii-values
        self.logger.info(f"Changing Program name to {new_name}")
        self.msg_bytes[56:] = list(map(ord, new_name))

    def send_cc(self, control, value):
        msg = mido.Message('control_change')
        msg.control = control
        msg.value = value
        self.outport.send(msg)

    def send_pc(self, program):
        msg = mido.Message('program_change')
        msg.program = program
        self.outport.send(msg)

    def get_midioutputs(self):
        # helper function for the gui app
        return mido.get_output_names()

    def get_midiinputs(self):
        # helper function for the gui app
        return mido.get_input_names()

    # }}}

    # {{{ dump human readable
    def dump(self, prog_name):
        # TODO: Format the output so it can be used as a simple menu
        # (enter a number to change certain parameters, save, load,...)
        p_name = self.get_program_name()
        print(f"Program: {prog_name}")
        print(f"Program name: {p_name}")
        if self.msg_bytes[1] > 0:
            print("Distorton ON")
        if self.msg_bytes[2] > 0:
            print("Drive ENABLED")
        if self.msg_bytes[3] > 0:
            print("Presence ENABLED")
        if self.msg_bytes[4] > 0:
            print("Delay ENABLED")
        if self.msg_bytes[5] > 0:
            print("Tremolo/Chorus Flange ENABLED")
        if self.msg_bytes[6] > 0:
            print("Reverb ENABLED")
        if self.msg_bytes[7] > 0:
            print("Noise Gate ENABLED")
        if self.msg_bytes[8] > 0:
            print("Bright Switch ON")
        print("Amp Type: {}".format(line6.amp_names[self.msg_bytes[9]]))
        print("Cab Type: {}".format(line6.cab_names[self.msg_bytes[45]]))
        print("AIR: {}".format(self.msg_bytes[46]))
        print("Drive: {}".format(self.msg_bytes[10]))
        print("Drive 2: {}".format(self.msg_bytes[11]))
        print("Bass: {}".format(self.msg_bytes[12]))
        print("Mid: {}".format(self.msg_bytes[13]))
        print("Treble: {}".format(self.msg_bytes[14]))
        print("Presence: {}".format(self.msg_bytes[15]))
        print("Channel Volume: {}".format(self.msg_bytes[16] * 2))
        print("Noise Gate Threshhold: {}".format(self.msg_bytes[17] * 2))
        print("Noise Gate Decay Time: {}".format(self.msg_bytes[18] * 2))
        #19-25: Wah and Volume Pedal - since I don't have either, I will keep this out for now
        # FIXME: Since I added Wah info to the CC-Commands I will also add it here
        # Max delay time is 3150ms, bytes 28,29,30 contain the value*6 but only 14 bits (instead of 24)
        # so we divide by 6 and then multiply it with 0.192272 (that is 3150/0b11111111111111)
        delay_time = int(
            ((((self.msg_bytes[28] << 8) | self.msg_bytes[29]) << 8)
             | self.msg_bytes[30]) / 6)
        delay_time = int(delay_time * 0.192272)
        print("Delay Time: {}ms".format(delay_time))
        print("Delay Feedback: {}".format(self.msg_bytes[35]))
        print("Delay Level: {}".format(self.msg_bytes[37]))
        r_type = "Hall" if self.msg_bytes[39] == 1 else "Spring"
        print("Reverb Type: {}".format(r_type))
        print("Reverb Decay: {}".format(self.msg_bytes[40] * 2))
        print("Reverb Tone: {}".format(self.msg_bytes[41] * 2))
        print("Reverb Diffusion: {}".format(self.msg_bytes[42] * 2))
        print("Reverb Density: {}".format(self.msg_bytes[43] * 2))
        print("Reverb Level: {}".format(self.msg_bytes[44] * 2))
        print("FX: {}".format(line6.fx_names[self.msg_bytes[47]]))
        print("FX Tweak: {}".format(self.msg_bytes[48] * 2))
        comp = "OFF"
        if self.msg_bytes[47] == 7 or self.msg_bytes[47] == 11:
            if self.msg_bytes[49] == 1:
                comp = "1.4:1"
            if self.msg_bytes[49] == 2:
                comp = "2:1"
            if self.msg_bytes[49] == 3:
                comp = "3:1"
            if self.msg_bytes[49] == 4:
                comp = "6:1"
            if self.msg_bytes[49] == 5:
                comp = "INF:1"
            print("Compressor Ratio: {}".format(comp))
Ejemplo n.º 38
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)
Ejemplo n.º 39
0
# SETUP MIDI IO, just pick the first port, what could go wrong?
import mido
import re
midi_ports = mido.get_output_names()
midi_port = midi_ports[0]
for port in midi_ports:
    if re.match('IAC', port) or re.match('LoopBe', port):
        midi_port = port
outport = mido.open_output(midi_port)

midi_ports = mido.get_input_names()
for port in midi_ports:
    if re.match('IAC', port) or re.match('LoopBe', port):
        midi_port = port
inport = mido.open_input(midi_port)

MIDI_CHANNEL = 11
MIDI_NOTE = 36

import threading
NOTE_LENGTH = 0.25


def note_off():
    outport.send(mido.Message('note_off', note=MIDI_NOTE,
                              channel=MIDI_CHANNEL))


def note_on():
    outport.send(mido.Message('note_on', note=MIDI_NOTE, channel=MIDI_CHANNEL))
Ejemplo n.º 40
0
 def openInput(self, inputsArr, index):
     if len(inputsArr) > 0:
         return mido.open_input(inputsArr[index])
Ejemplo n.º 41
0
MINOR_SEVEN_CHORD = {}
for i, chord in enumerate(PITDH_LIST):
    MINOR_SEVEN_CHORD["{}m7".format(chord)] = {"list": [(note + i) % 12 for note in C_MINOR_7],
                                               "root_note": i,
                                               "root": chord,
                                               }
CHORD_FROM_3.update(MINOR_SEVEN_CHORD)

MAJOR_AND_MINOR_CHORD = MAJOR_CHORD
MAJOR_AND_MINOR_CHORD.update(MINOR_CHORD)
print(mido.get_input_names())
print(mido.get_output_names())

# inport = mido.open_input("loopMIDI Port 1")
inport = mido.open_input("Q49 0")
outport = mido.open_output("loopMIDI Port 2")
note_on_list = []


def note_to_pitch(note):
    return PITDH_LIST[note % 12]


def convert_to_base_note(note_list):
    base_note_list = []
    for note in note_list:
        base_note = note % 12
        if base_note not in base_note_list:
            base_note_list.append(base_note)
    return base_note_list
Ejemplo n.º 42
0
 &&&&&  &&&&&&  &&&&&& &&&&&&  &&&&&  &&&&&   &&&&&&
 &&&&&  &&&&&   &&&&&  &&&&&&  &&&&&  &&&&&   &&&&&& ,&&&&&
 &&&&&&&&&      &&&&&  &&&&&&  &&&&&&&&&&     &&&&&& ,&&&&&
 &&&&&  &&&&&   &&&&&  &&&&&&  &&&&&  &&&&&   &&&&&& ,&&&&&
 &&&&&  &&&&&&  &&&&&. &&&&&&  &&&&&  &&&&&&  &&&&&& #&&&&&
 &&&&&  %&&&&&   &&&&&&&&&&&   &&&&&   &&&&&/  &&&&&&&&&&&&
"""

TIMESTAMP = datetime.now().strftime('%Y%m%d-%H%M')
A4_DATA_SIZE = 725

print (LOGO)
print(" --[ KORG A4 MIDI Dump ] --\n")


midi_in_port = mido.open_input('Studio 1810c')
print("[READY] Waiting for MIDI data from A4]")
midi_msg = midi_in_port.receive()
sysex_data = midi_msg.data

if len(sysex_data) == A4_DATA_SIZE:
    print("[SUCCESS] Data Read Successful")

    patch_data = [mido.Message('sysex', data=sysex_data)]
    file_name_text = f"korg-a4-patches-{TIMESTAMP}.txt"
    file_name_raw = f"korg-a4-patches-{TIMESTAMP}.sysex"

    try:
        mido.write_syx_file(file_name_text, patch_data, plaintext=True)
        mido.write_syx_file(file_name_raw, patch_data, plaintext=False)
        print (f"[SUCCESS] Data written to {file_name_text}, {file_name_raw}")
Ejemplo n.º 43
0
import mido

mido.get_input_names()
mido.get_output_names()
port2 = mido.open_output('loopMIDI Port 2 3')
channel = 2
channel_max = 3
try:
    with mido.open_input('loopMIDI Port 0') as inport:
        while True:
            for msg in inport:
                print(msg)
                #print(dir(msg))
                if msg.type == 'control_change' and msg.control == 1:
                    channel += 1
                    # channel = 0
                    if channel > channel_max:
                        channel = 2
                else:
                    msg_copy = msg
                    msg_copy.channel = channel
                    # output = mido.Message(msg.type, note=msg.note, velocity=msg.velocity, channel=2)
                    port2.send(msg_copy)
                    print(msg_copy)
                    print('sent on channel {}'.format(channel))
except:
    pass
Ejemplo n.º 44
0
def obs_start():
    obs_ws.run_forever()


def scalemap(inp, ista, isto, osta, osto):
    return osta + (osto - osta) * ((inp - ista) / (isto - ista))


if __name__ == "__main__":
    print("MIDItoOBS made by github.com/lebaston100")
    print("!!MAKE SURE OBS IS RUNNING OR THIS SCRIPT WILL CRASH!!")
    print("Main program started")
    result = db.search(Query().type.exists())
    if result:
        try:
            port = mido.open_input(result[0]["value"], callback=midicallback)
        except:
            print(
                "The midi device you setup is not connected or now under a different name."
            )
            print(
                "Please plugin in the device or run setup.py again and restart this script."
            )
            time.sleep(8)
            sys.exit()
        obs_ws = websocket.WebSocketApp("ws://" + serverIP + ":" + serverPort,
                                        on_message=obs_on_message,
                                        on_error=obs_on_error,
                                        on_close=obs_on_close)
        obs_ws.on_open = obs_on_open
        atexit.register(exitScript)
Ejemplo n.º 45
0
def openIn(deviceName):
    inputPort = chooseDevice(mido.get_input_names(), deviceName)
    if inputPort:
        return mido.open_input(inputPort)
    else: 
        return None
Ejemplo n.º 46
0
import mido
from mido import Message

outport = mido.open_output('Base2 MIDI 1')
inport = mido.open_input('Base2 MIDI 1')

for msg in inport:
    msgout = msg
    if hasattr(msg, 'note'):
        msgout.note = msgout.note + 4
        outport(msgout)
Ejemplo n.º 47
0
tapper_off = 20000

volume = 0.5  # range [0.0, 1.0]
fs = 44100  # sampling rate, Hz, must be integer
duration = 0.75  # in seconds, may be float


def play_note(note_value):
    note_mapper = (2.0**((note_value - 69) / 12.0)) * 440.0
    samples = np.sin(2 * np.pi * np.arange(fs * duration) * note_mapper /
                     fs).astype(np.float32)
    for i in range(tapper_off):
        samples[-i - 1] = samples[-i - 1] * i / float(tapper_off)

    stream.write(volume * samples)


p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=fs,
                input=True,
                output=True)

index = 0
for msg in mido.open_input():
    print(msg)
    if msg.type == 'note_on':
        play_note(msg.note)
Ejemplo n.º 48
0
content = [x for x in content if x[0] != '#']
content = [x.split('=') for x in content]

#convert config to dict
config = dict()
for element in content:
    config[element[0]] = element[1]

if config['LCD'] == 'true':
    lcd = LcdHandler(int(config['LCD_ROWS']), int(config['LCD_COLS']))
else:
    lcd = None

try:
    #midiin = rtmidi.MidiIn()
    port = mido.open_input(callback=MidiInputHandler(lcd))
    #port_name = midiin.open_virtual_port("MidiSniffer")
    #midiin.ignore_types(sysex=False)
except (EOFError, KeyboardInterrupt):
    sys.exit()

print("Attaching MIDI input callback handler.")
#midiin.set_callback(MidiInputHandler(port_name, lcd))

print("Entering main loop. Press Control-C to exit.")
try:
    # Just wait for keyboard interrupt,
    # everything else is handled via the input callback.
    while True:
        sleep(1)
except KeyboardInterrupt:
Ejemplo n.º 49
0
Archivo: midido.py Proyecto: 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)
Ejemplo n.º 50
0
        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():
		note = find_between(str(msg), "note=", " ")
		original_note = note
		note = int(note)
		if "note_off" in str(msg):
			velocity = 0
Ejemplo n.º 51
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)
Ejemplo n.º 52
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()

# 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():

        if debug > 0:
            print msg

        if hasattr(msg, "control"):
Ejemplo n.º 53
0
 def listen(self):
     with mido.open_input(self.inputs[0]) as port:
         start = time.time()
         for msg in port:
             if not self.pause:
                 self.queue.append((msg, time.time() - start))
Ejemplo n.º 54
0
    system('say ' + text)
    waiting = (len(text) / 7)
    time.sleep(1 + waiting)
    if restart:
        system('./config.sh start')


# my_say(" First test")
# my_say(" This is my very first test. You should see config.sh appear later than before")
# my_say(" And now it should appear much faster")

pressed_notes = []
times_up = False
correct_answer = False
with mido.open_input(input1) as inport:
    while (True):

        thechord = choose_random_chord()
        chord_name, parsed_chord = parse_chord(thechord)
        print(parsed_chord)
        print(chord_name)
        say_chord(chord_name[0])

        times_up = False
        correct_answer = False
        for msg in inport:
            if 'note' not in dir(msg):
                continue

            if msg.is_meta:
Ejemplo n.º 55
0
    except Exception as err:
        print(err)
        print("connect failed")


def wsSendWithTry(toSend):
    global ws

    try:
        ws.send(toSend)
    except:
        traceback.print_exc()


while True:
    with mido.open_input('IAC Driver IAC Bus 1') as inport:
        # print inport
        for msg in inport:
            print(msg)
            if msg.type == "note_on":
                print(msg.note)

                if msg.note == 0:
                    wsSendWithTry(
                        json.dumps({
                            'message': 'videoplay',
                            'url': '1912008_hauntedNight_HD_BG.mp4',
                            'looping': 'looping',
                            'instance': 'overlay',
                            'type': 'mp4'
                        }))
def monitor_midi():  #Monitor new midi messages
    with mido.open_input('HDSPMx73554b MIDI 3') as port:
        for message in port:
            if message.type != 'quarter_frame':
                last_time = message
                print last_time
Ejemplo n.º 57
0
def main():
    """ The main loop """
    status_color = None

    animations = []
    leds = [(0, 0, 0)] * PIANO_KEYS

    usb_device_name = detect_midi_device()
    if usb_device_name:
        print("Opening {0} port".format(usb_device_name))
        midi_input = mido.open_input(usb_device_name)
    else:
        print("No MIDI device detected")
        midi_input = None

    print("Starting main loop...")

    configuration['mode'] = 'demo'
    configuration['gamma_correction'] = False
    configuration['animation'] = 1
    configuration['demo_delay'] = 60 * 5
    configuration['demo_done'] = 60 * 60
    configuration['status_brightness'] = 255

    # Start in demo on startup
    last_key_time = time.time() - configuration['demo_delay']

    STRIP.begin()
    STRIP.show()

    # Used to detect the "secret chord" for controlling various aspects
    chord = set()

    #running_animation = animation.RunningAnimation(PIANO_KEYS)
    #animations.append(running_animation)
    practice_timer = timer.Timer()
    animations.append(practice_timer)
    #animations.append(animation.BeatAnimation(44, 80))

    try:

        while True:
            idle_time = time.time() - last_key_time
            if idle_time > configuration['demo_done']:
                if configuration['mode'] != 'sleep':
                    configuration['mode'] = 'sleep'
                    status_color = 0x000000
                    STRIP.clear()
                    STRIP.show()
            elif idle_time > configuration['demo_delay']:
                if configuration['mode'] != 'demo':
                    configuration['mode'] = 'demo'
                    # Hide "forever" while in demo mode. TODO: Improve with special case.
                    practice_timer.hide(1000 * 60 * 60 * 24 * 365)
            elif configuration['mode'] != 'midi':
                configuration['mode'] = 'midi'

            # Apply an optional filter (default is to black out LEDs).
            # For now, directly clear the buffer.
            leds = [(0, 0, 0)] * PIANO_KEYS

            if set([0, 1]).issubset(chord):
                print("Secret chord pressed")

                if 2 in chord:
                    print("Red status lights")
                    status_color = 0xFF0000
                if 3 in chord:
                    status_color = 0x00FF00
                if 4 in chord:
                    status_color = 0x0000FF
                if 5 in chord:
                    status_color = 0xFFFFFF
                if 6 in chord:
                    status_color = 0xFFFC7F
                if 7 in chord:
                    status_color = 0x000000

                draw_status(status_color)

                # 15 is the second C note from the left. Toggle brightness down.
                if 15 in chord:
                    configuration['status_brightness'] -= 1
                    if configuration['status_brightness'] < 1:
                        configuration['status_brightness'] = 1
                    draw_status(status_color)
                # 16 is the second D note from the left. Toggle brightness up.
                if 17 in chord:
                    configuration['status_brightness'] += 1
                    if configuration['status_brightness'] > 255:
                        configuration['status_brightness'] = 255
                    draw_status(status_color)

                if 14 in chord:
                    practice_timer.restart()

            #for i, pixel in enumerate(leds):
            #    r, g, b = (pixel)
            #    leds[i] = (int(r/1.2), int(g/1.2), int(b/1.2))

            for current_animation in animations:
                new_frame = current_animation.get_frame()
                for i, frame_pixel in enumerate(new_frame):
                    r, g, b = (frame_pixel)
                    if r > 0 or g > 0 or b > 0:
                        leds[i] = color_blend(leds[i], frame_pixel)

            animations = [x for x in animations if not x.is_complete()]

            for i, pixel in enumerate(leds):
                r, g, b = (pixel)
                if configuration['gamma_correction']:
                    r = GAMMA[r]
                    g = GAMMA[g]
                    b = GAMMA[b]
                STRIP.setPixelColor(i, r, g, b)

            STRIP.show()

            # Experiment to see how long we need to sleep - it seems that this may cause problems
            # if too short
            time.sleep(0.01)

            if midi_input is not None:
                for message in midi_input.iter_pending():
                    print(message)
                    last_key_time = time.time()
                    practice_timer.hide(10 * 1000)
                    if message.type == 'note_on':
                        note = message.note - FIRST_MIDI_NOTE
                        chord.add(note)
                        #running_animation.key_pressed(message.velocity * 2)
                        animations.append(
                            animation.PressureKeyPressAnimation(
                                PIANO_KEYS, note, message.velocity * 2, 3000))
                        #animations.append(animation.ChristmasKeyPressAnimation(PIANO_KEYS, note, message.velocity * 2))
                        #animations.append(animation.RunLeftAnimation(note))
                        #animations.append(animation.LightUpAnimation(PIANO_KEYS, note))
                    if message.type == 'note_off':
                        note = message.note - FIRST_MIDI_NOTE
                        if note in chord:
                            chord.remove(note)

            if configuration['mode'] == 'demo':
                if randint(0, 15) == 0:

                    # Here we would get a key press
                    key_pressed = randint(0, PIANO_KEYS - 1)

                    animations.append(
                        animation.ChristmasKeyPressAnimation(
                            PIANO_KEYS, key_pressed, randint(1, 255), 1000))
                    #animations.append(animation.PressureKeyPressAnimation(PIANO_KEYS, key_pressed, randint(1, 255), 1000))
                    #animations.append(animation.KeyPressAnimation(PIANO_KEYS, key_pressed))
                    #animations.append(animation.RunLeftAnimation(key_pressed))

    except KeyboardInterrupt:
        print("Exiting...")
        STRIP.clear()
        STRIP.show()
        STRIP.close()
        if midi_input:
            midi_input.close()
Ejemplo n.º 58
0
import mido

outport = mido.open_output('Springbeats vMIDI1 2')

with mido.open_input('Babyface Midi Port 1 0') as inport:
    for msg in inport:
        print(msg)
        outport.send(msg)  #just send the message right through








Ejemplo n.º 59
0
 def open_device(self, device_name, callback):
     self.inport = mido.open_input(device_name)
     self.inport.callback = callback
Ejemplo n.º 60
0
import mido
from ConfigurationSetup import *

#configuration Setup
cfgFile="config.cfg"
config=parse_cfg(cfgFile)

#receive Data
with mido.open_input(config["inPort"]) as inputPort:
    for msg in inputPort:
        print (msg)