Example #1
0
File: lpd8.py Project: zetof/boing
    def __init__(self, program=3, bank=0, buffer_size=50):
        """
        Class constructor
        Note that buffer_siez has been set to 50 and is a recommended value for LPD8
        It allows turning control knobs full speed without choking the reader
        :param program: numeric value from 0 to 3 corresponding to choice triggered by PROGRAM key on LPD8
        :param bank: numeric value from 0 to 7  corresponding to choice triggered by PROG/CHNG key on LPD8
        :param buffer_size: MIDI buffer size for read operations
        """

        # Store class properties
        self._program = program
        self._bank = bank
        self._buffer_size = buffer_size

        # Searching for LPD8 in available MIDI devices
        print('starting midi...')
        midi.init()
        nb_of_devices = midi.get_count()
        id = 0
        while id < nb_of_devices:
            infos = midi.get_device_info(id)
            if (infos[1] == b'LPD8' and infos[2] == 1):
                break
            id += 1
        try:
            self._lpd8_in = midi.Input(id, buffer_size)
            self._ctrl_knob_array = LPD8_Ctrl_Knob_Array()
            print('LPD8 input device connected...')
        except midi.MidiException:
            self._lpd8_in = None
            print('LPD8 input device not found...')
Example #2
0
    def _open(self, **kwargs):
        if kwargs.get('virtual'):
            raise ValueError('virtual ports are not supported'
                             ' by the Pygame backend')
        elif kwargs.get('callback'):
            raise ValueError('callbacks are not supported'
                             ' by the Pygame backend')

        midi.init()

        if self.name is None:
            device = _get_default_device(self.is_input)
            self.name = device['name']
        else:
            device = _get_named_device(self.name, self.is_input)

        if device['opened']:
            if self.is_input:
                devtype = 'input'
            else:
                devtype = 'output'
            raise IOError('{} port {!r} is already open'.format(
                devtype, self.name))
        if self.is_input:
            self._port = midi.Input(device['id'])
        else:
            self._port = midi.Output(device['id'])

        self._device_type = 'Pygame/{}'.format(device['interface'])
Example #3
0
    def _open(self, **kwargs):
        if 'virtual' in kwargs:
            raise IOError(
                "virtual ports are not supported by the Pygame backend")

        midi.init()

        opening_input = hasattr(self, 'receive')

        if self.name is None:
            device = _get_default_device(opening_input)
            self.name = device['name']
        else:
            device = _get_named_device(self.name, opening_input)

        if device['opened']:
            if opening_input:
                devtype = 'input'
            else:
                devtype = 'output'
            raise IOError('{} port {!r} is already open'.format(
                devtype, self.name))
        if opening_input:
            self._port = midi.Input(device['id'])
        else:
            self._port = midi.Output(device['id'])

        self._device_type = 'Pygame/{}'.format(device['interface'])
Example #4
0
    def __init__(self, debug=False):
        print('Using Pygame MIDI interface')
        self.debug = debug

        midi.init()

        self.midi_input = None
        for device_id in range(midi.get_count()):
            interf, name, is_input, is_output, opened = midi.get_device_info(
                device_id)
            interf = interf.decode('utf-8')
            name = name.decode('utf-8')
            imode = 'input' if is_input else 'output' if is_output else 'none'
            iopen = '(open)' if opened else ''

            if self.debug:
                print(f'{interf} / {name} ({imode}) {iopen}')

            if name in known_devices and is_input:
                self.midi_input = midi.Input(device_id)
                self.midi_input.name = f'{name} ({imode})'
                print(f'Using midi input device {name}')
                break

        self.binds = {}
        self.running = True
        self.done = False
Example #5
0
    def _open(self):
        midi.init()

        self.device = None

        opening_input = (self.__class__ is Input)

        if self.name is None:
            self.device = self._get_default_device(opening_input)
            self.name = self.device['name']
        else:
            self.device = self._get_named_device(self.name, opening_input)

        if self.device['opened']:
            if opening_input:
                devtype = 'input'
            else:
                devtype = 'output'
            raise IOError('{} port {!r} is already open'.format(
                devtype, self.name))

        if opening_input:
            self._port = midi.Input(self.device['device_id'])
        else:
            self._port = midi.Output(self.device['device_id'])

        atexit.register(self.close)
Example #6
0
 def openById(self, id):
     dev = self.devices[id]
     if dev["direction"] == "OUTPUT":
         self.midiDevice = midi.Output(dev["device"])
     if dev["direction"] == "INPUT":
         self.midiDevice = midi.Input(dev["device"])
     return self.midiDevice
Example #7
0
    def run(self):
        pygame.midi.init()
        self.device_id = midi.get_default_input_id()
        
        if self.device_id == NO_DEVICE_FOUND:
            raise NoPianoDetectedException('Device not detected.')
        
        self.midiObject = midi.Input(self.device_id)
        
        pygame.init()
        self._resize_surface((WIDTH, HEIGHT))
        clock = pygame.time.Clock()
        
        if DEBUG_TRACE:
            interface, name, is_input, is_output, is_open = midi.get_device_info(self.device_id)
            print('Device Interface: ', interface)
            print('Device Name: ', name)
            print('Device IsInput: ', is_input == 1)
            print('Device IsOutput: ', is_output == 1)
            print('Device Open: ', is_open == 1)

        self._game = GameModes.PressNext((WIDTH, HEIGHT))
        
        while(True):
            clock.tick(MAX_FRAMES_PER_SECOND)
            self._event_handler()
            
        self.midiObject.close()
        midi.quit()
Example #8
0
    def __init__(self, device, buffer_size=None):
        """Create a MIDI input.

        Parameters
        ----------
        device : int or str
            id or name of the MIDI device
        buffer_size : int, optional
            number of events to be buffered

        """

        import types
        if type(_midi) is not types.ModuleType:
            raise ImportError("""Sorry, MIDI input is not supported on this computer.""")

        if not expyriment._active_exp.is_initialized:
            raise RuntimeError(
                "Cannot create MidiIn before expyriment.initialize()!")
        _midi.init()
        Input.__init__(self)
        self._id = device
        if buffer_size is None:
            buffer_size = defaults.midiin_buffer_size
        self._buffer_size = buffer_size
        self.input = _midi.Input(device, buffer_size)
Example #9
0
	def __init__(self, **kwargs):
		"""Keywords are 'input_id', 'output_id' and 'chan'"""
		if kwargs is not None:
			if 'input_id' in kwargs.keys():
				self.input_id = kwargs['input_id']
				# Create streams
				self.inStream = Midi.Input(self.input_id)
			#If given an output id, assign it a variable
			if 'output_id' in kwargs.keys():
				self.output_id = kwargs['output_id']
				# Create streams
				self.outStream = Midi.Output(self.output_id)
			if 'chan' in kwargs.keys():
				self.chan = kwargs['chan']
			else:
				#Use chan 0 on default
				self.chan = 0
		else:
			raise Exception("At least on id must be given")

		#Init variables
		self.receiving_sysEx = False
		self.sysExMsg = []
		#Create status messages. Should maybe not be constant for devices, but is sufficient for my needs now.
		self.key_on_status_with_chan = (self.KEY_ON_ID << 4) | self.chan
		self.key_off_status_with_chan = (self.KEY_OFF_ID << 4) | self.chan
Example #10
0
 def OpenInput(self, midi_id):
     if self.devIn is None:
         try:
             self.devIn = midi.Input(midi_id, MIDI_BUFFER_IN)
         except:
             self.devIn = None
             return False
     return True
Example #11
0
 def openByName(self, name, direction):
     for dev in self.devices:
         if (dev["name"] == name) & (dev["direction"] == direction):
             if direction == "OUTPUT":
                 self.midiDevice = midi.Output(dev["device"])
             if direction == "INPUT":
                 self.midiDevice = midi.Input(dev["device"])
     return self.midiDevice
Example #12
0
def open_stream(name):
    ''' Searches for a MIDI input device matching the passed name and opens
        a stream. If name=None, opens the first input device.
    '''
    for i in range(255):
        info = midi.get_device_info(i)
        if (name is None or info[1].decode() == name) and info[2] == 1:
            return midi.Input(i)
Example #13
0
def set_in_device(name):
    global m_in
    if m_in:
        m_in.close()
    for in_d in inDevices():
        if in_d[0] == name:
            m_in = pm.Input(in_d[1])
            return True
    return False
Example #14
0
    def __init__(self, input_device_id, melodies, output_device_id=None):
        self.melodies = melodies
        self.midi_input = midi.Input(input_device_id)
        self.midi_output = None
        if output_device_id is not None:
            self.midi_output = midi.Output(output_device_id,
                                           buffer_size=8,
                                           latency=1)

        self.pitches = {}
        self.continue_processing = True
Example #15
0
    def input_port(self):

        for a in range(midi.get_count()):
            device = midi.get_device_info(a)
            name = str(device[1]).lower()
            if ("launchpad" in name and device[2]):
                id = a
                if (self.mode != "live"):
                    id = a + 1
                return midi.Input(id)
        return False
    def setDevice(self, idnum):
        r = pm.get_device_info(idnum)
        if r is not None:
            self.device = pm.Input(idnum)

            self.device_id = idnum
            self.device_name = r[1]
            if r[2]:
                self.device_type = "input"
            elif r[3]:
                self.device_type = "output"
            self.device_opened = r[4]
Example #17
0
 def _input_device(self, device_id: int):
     """
     Create new Input object. 
     Catches MidiException if no controller found or none configured.
     """
     try:
         self._midi_active = True
         return midi.Input(device_id)
     except MidiException:
         self._midi_active = False
         self.close_controller()
         return None
Example #18
0
 def __init__(self):
     infos = [midi.get_device_info(n) for n in range(0, midi.get_count())]
     i = 0
     o = 0
     for (n, info) in enumerate(infos):
         if info[2] and "Launchpad" in info[1]:
             i = n
         elif info[3] and "Launchpad" in info[1]:
             o = n
     print "Detected Launchpad on input " + str(i) + " and output " + str(o)
     self.input = midi.Input(i)
     self.output = midi.Output(o)
     print "Connection established"
Example #19
0
 def __init__(self, midiin_id, midiout_id):
     self.midiin_id = midiin_id
     self.midiout_id = midiout_id
     pg.init()
     pg.fastevent.init()
     midi.init()
     self._screen = pg.display.set_mode(WINDOW_SIZE)
     self._clock = pg.time.Clock()
     self._midin = midi.Input(midiin_id)
     self._midout = midi.Output(midiout_id)
     self._font = pg.font.Font('freesansbold.ttf', 32)
     self.note = 0
     self.render_text("")
Example #20
0
    def __init__(self, input, output, flash=True):
        midi.init()
        while not midi.get_init():
            pass

        self._midiIn = midi.Input(input)
        self._midiOut = midi.Output(output)

        if flash:
            for i in (5, 3, 1, 0):
                for j in range(64):
                    self._midiOut.note_on(j, i)
                    time.sleep(0.01)
Example #21
0
 def __init__(self, Input=1, Output=3, PadConfig={}, bypassexit=False):
     try:
         midi.init()
         self.In = midi.Input(Input, 1024)
         self.Out = midi.Output(Output, 1024)
     except:
         PrintError("Midi Pad not found")
         if not bypassexit:
             PrintError("Exiting program")
             exit()
     else:
         PrintWithTime("Connected Midi Pad")
     self.Pad = PadConfig
Example #22
0
    def init(self):
        pg.init()
        pgm.init()

        pg.fastevent.init()
        self.event_get = pg.fastevent.get
        self.event_post = pg.fastevent.post

        # print_device_info()

        print(f'Available resolutions: {pg.display.list_modes()}')
        if not self.midi_input_id:
            self.midi_input_id = detect_input_device()
        if not self.midi_output_id:
            self.midi_output_id = detect_output_device()
        self.midi_in = pgm.Input(self.midi_input_id)
        self.midi_out = pgm.Output(self.midi_output_id)

        infoObject = pg.display.Info()

        self.w = infoObject.current_w
        self.h = infoObject.current_h

        # FULLSCREEN has this problem: https://github.com/pygame/pygame/issues/2538
        # Using the workaround there.
        self.screen = pg.display.set_mode([0, 0], pg.NOFRAME | pg.DOUBLEBUF
                                          | pg.HWSURFACE)
        # pg.display.toggle_fullscreen()
        pprint(self.screen)
        pg.display.set_caption('Velocity Visualizer')

        icon = pg.image.load(os.path.dirname(__file__) + '/piano.png')
        pg.display.set_icon(icon)

        self.w = self.screen.get_width()
        self.h = self.screen.get_height()
        # print(f"{w} x {h}")
        self.hm = self.w * HORIZONTAL_MARGIN
        self.vm = self.h * VERTICAL_MARGIN

        print(int(self.w - self.hm * 2), int(self.h - self.vm * 2))
        self.roll = pg.Surface(
            (int(self.w - self.hm * 2), int(self.h - self.vm * 2)))
        self.roll.fill((0, 0, 0))
        self.roll_tick = 0

        self.reset_midi_out()

        self.initialized = True

        return self
Example #23
0
    def getMidi(self):
        midIn = m.Input(m.get_default_input_id())
        while not midIn.poll() and self.running:
            if not m.get_init():
                m.init()
            else:
                pass
        if not self.running:
            return

        event = midIn.read(1)
        mob = mObject(event[0][0][0] >> 4, event[0][0][1], event[0][0][2])
        midIn.close()
        return mob
Example #24
0
def selectInput():
    index = 0
    midi_input = None
    while 1:
        description =  midi.get_device_info(index)
        if description != None:
            if description[3] == 0: # it's a midi output
                print("%i %s"%(index, description[1]))
            index += 1
        else:
            break
    txt = input("Select a midi input device")
    if txt != "":
        midi_input = midi.Input(int(txt))
    return midi_input
Example #25
0
    def __init__(self):
        midi.init()

        try:
            if (midi.get_count() < 1):
                logger.error("no MIDI device connected")
                sys.exit(-1)
        except SystemExit:
            raise
        except:
            logger.error("MIDI not available")
            sys.exit(-2)

        self.name = midi.get_device_info(0)[1]
        self.input_stream = midi.Input(0, 16)
        self.output_stream = midi.Output(1, 128)
Example #26
0
 def run(self):
     midi.init()
     i = [
         i for i in range(midi.get_count())
         if self._name in midi.get_device_info(i)[1]
     ][0]
     i = midi.Input(i)
     while not self._halt:
         e = i.read(1)
         if len(e):
             e = e[0][0]
             if e[2] and (36 <= e[1] <= 84):
                 #print(e[1])
                 self._on_note(music.midi_note(e[1]))
         else:
             sleep(.001)
     i = None
Example #27
0
    def mainloop(self,
                 inputdeviceid=None,
                 outputdeviceid=None,
                 ignoreerror=False,
                 highervelocity=False):
        midi.init()

        try:
            inputdeviceid = inputdeviceid if inputdeviceid is not None else midi.get_default_input_id(
            )
            print("MIDI Input:", midi.get_device_info(inputdeviceid))
            self._midi_in = midi.Input(inputdeviceid)
        except midi.MidiException as e:
            if ignoreerror:
                self._midi_in = None
                print("No MIDI In!", e)
            else:
                raise e

        try:
            outputdeviceid = outputdeviceid if outputdeviceid is not None else midi.get_default_output_id(
            )
            print("MIDI Output:", midi.get_device_info(outputdeviceid))
            self._midi_out = midi.Output(outputdeviceid)
            self._midi_out.set_instrument(0)
        except (midi.MidiException, Exception) as e:
            if ignoreerror:
                print("No MIDI Out!", e)
                self._midi_out = None
            else:
                raise e

        if self._midi_in:
            while True:
                if self._midi_in.poll():
                    events = self._midi_in.read(10)
                    for event in events:
                        self._parse_midi_event(event,
                                               highervelocity=highervelocity)
                try:
                    self._root.update()
                except:
                    midi.quit()
                    break
        else:
            self._root.mainloop()
Example #28
0
 def open(self, device_name=DEFAULT_DRIVER_NAME):
     try:
         for index, device in enumerate(self.devices):
             (interface, name, is_input, is_output, is_opened) = device
             if name.decode("utf-8") == device_name:
                 if is_input:
                     self.input = midi.Input(index)
                 if is_output:
                     self.output = midi.Output(index)
                 if self.input and self.output:
                     break
         if self.input is None or self.output is None:
             raise Exception(f'{device_name} does not exist.\nAvailable devices: {[x[1] for x in self.devices]}')
         self.get_config()
     except Exception as e:
         self._end()
         raise e
Example #29
0
def main():
    global bpm
    global skip
    global pad_in
    global pad_out
    global in_chan
    global out_chan
    global fastmode
    if not len(sys.argv[1:]):
        usage()
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "hb:sfi:o:",
            ["help", "bpm", "skip", "fast", "input", "output"])
    except getopt.GetoptError as err:
        print str(err)
        usage()
    if len(args):
        usage()
    for o, a in opts:
        if o in ["-h", "--help"]:
            usage()
        elif o in ["-b", "--bpm"]:
            bpm = float(a)
        elif o in ["-s", "--skip"]:
            skip = True
        elif o in ["-f", "--fast"]:
            fastmode = True
        elif o in ["-i", "--input"]:
            in_chan = int(a)
        elif o in ["-o", "--output"]:
            out_chan = int(a)
        else:
            assert False, "Unhandled Option"
    if midi.get_device_info(in_chan) != ('ALSA', 'Launchpad S MIDI 1', 1, 0,
                                         0):
        print "[!] Launchpad input channel invalid"
        sys.exit(0)
    if midi.get_device_info(out_chan) != ('ALSA', 'Launchpad S MIDI 1', 0, 1,
                                          0):
        print "[!] Launchpad output channel invalid"
        sys.exit(0)
    pad_in = midi.Input(in_chan)
    pad_out = midi.Output(out_chan)
    loop()
Example #30
0
def connect_midi():
	global default_midi_input
	midi_in = None
	while midi_in == None:
		try:
			midi_in = midi.Input(int(default_midi_input), 1024)
			print("Connected to default midi device")
			return midi_in
		except Exception as e:
			print(f"Connection to default midi device failed. Error: {e}")
			print("Choose a device (num) or manual mode (m)")
			for i in range(midi.get_count()):
				info = midi.get_device_info(i)
				if info[2]:
					print(i, info)
			default_midi_input = input("->")
			if default_midi_input == "m":
				return False