Esempio n. 1
0
def midi_info():
    """
    midi is an instance of pygame.midi

    Returns a dictionary containing info
        about the systems MIDI devices.
    The dictionary contains:
        'count' - number of devices.
        'def_in' - default input.
        'def_out' - default output.
        'devices' - a list of device info.
    """

    info = {}
    #Store info.
    info.keys().append('count')
    info['count'] = midi.get_count()

    info.keys().append('def_in')
    info['def_in'] = midi.get_default_input_id()

    info.keys().append('def_out')
    info['def_out'] = midi.get_default_output_id()

    devices = []
    for i in range(0, midi.get_count()):
        devices.append(midi.get_device_info(i))

    info.keys().append('devices')
    info['devices'] = devices

    return info
Esempio n. 2
0
def main():
    """Initiates program and loop."""
    pygame.init()
    midi.init()

    print "Number of MIDI devices:", midi.get_count()
    if midi.get_count() == 0:
        print "No MIDI devices detected :P"
        return
    
    out_device = midi.get_default_output_id()
    if out_device == -1:
        print "No MIDI output device detected :P"
        return
    
    print "Uses device no:", out_device
    try:
        output = midi.Output( out_device )
        output.set_instrument( instrument )
        keyboard = init_keyboard(53)
        
        screen = pygame.display.set_mode([250,80])
        screen.fill((0,0,0))
        pygame.display.set_caption("MIDI Keyboard")
        pygame.display.flip()
        
        io_loop(keyboard, output, instrument)
        
    finally:
        del output
        midi.quit()
    def __init__(self):

        self.devIn = None
        self.devOut = None

        midi.init()

        # TODO: this sucks...
        try:
            midi.get_count()
        except:
            print("ERROR: MIDI not available...")
Esempio n. 4
0
    def __init__(self):

        self.devIn = None
        self.devOut = None

        midi.init()

        # TODO: this sucks...
        try:
            midi.get_count()
        except:
            print("ERROR: MIDI not available...")
def getInputDevices():
    for i in xrange(midi.get_count()):
        info = midi.get_device_info(i)
        (unusedInterface, name, isInput,
         unusedIsOutput, unusedOpened) = info
        if isInput:
            yield i, name
Esempio n. 6
0
File: lpd8.py Progetto: 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...')
Esempio n. 7
0
	def get_device(self, dev_name):
		for i in xrange(0, midi.get_count()):
			name = midi.get_device_info(i)[1]
			print midi.get_device_info(i)
			if name == dev_name:
				if midi.get_device_info(i)[3]: #Checking if output device
					return midi.Output(i)
Esempio n. 8
0
    def getMIDIDevices(self):
        midiOutputDevices = []
        midiInputDevices = []
        for index in xrange(0, midi.get_count()):
            device = midi.get_device_info(index)
            deviceName = device[1]
            if device[3] == 1 and device[4] == 0: #if the device is an output and not opened
                setattr(self, deviceName, QtGui.QAction(QtGui.QIcon(''), deviceName, self))
                deviceWidget = getattr(self, deviceName)
                deviceWidget.setCheckable(True)
                midiOutputDevices.append(deviceWidget)
                self.midiOutputDevicesDict[deviceWidget] = index
            elif device[2] == 1 and device[4] == 0: #if devices is an input and not opened
                deviceName = device[1]
                setattr(self, deviceName, QtGui.QAction(QtGui.QIcon(''), deviceName, self))
                deviceWidget = getattr(self, deviceName)
                deviceWidget.setCheckable(True)
                midiInputDevices.append(deviceWidget)
                self.midiInputDevicesDict[deviceWidget] = index
                
        if midiOutputDevices:
            self.ui.midiOutputDevicesMenu = self.ui.menubar.addMenu("&Midi Output Device")
            self.ui.midiOutputDevicesMenu.addActions(midiOutputDevices)
        if midiInputDevices:
            self.ui.midiInputDevicesMenu = self.ui.menubar.addMenu("&Midi Input Devices")
            self.ui.midiInputDevicesMenu.addActions(midiInputDevices)
        
        for device in midiOutputDevices:
            outputFunction = partial(self.windowHandler.midiOutputSelect, mainWindowInstance=self, device=device)
            device.triggered.connect(outputFunction)

        for device in midiInputDevices:
            inputFunction = partial(self.windowHandler.midiInputSelect, mainWindowInstance=self, device=device)
            device.triggered.connect(inputFunction)
Esempio n. 9
0
def input_device_ids():
    device_ids = []
    for device_id in range(midi.get_count()):
        info = midi.get_device_info(device_id)
        if info[IN] == 1:
            device_ids.append(device_id)
    return device_ids
Esempio n. 10
0
 def get_device(self, dev_name):
     for i in xrange(0, midi.get_count()):
         name = midi.get_device_info(i)[1]
         print midi.get_device_info(i)
         if name == dev_name:
             if midi.get_device_info(i)[3]:  #Checking if output device
                 return midi.Output(i)
Esempio n. 11
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
Esempio n. 12
0
 def __getDeviceId(self, midiport):
     n_device = pm.get_count()
     foundId = -1
     for id in range(n_device):
         if int(pm.get_device_info(id)[1] == midiport.encode()) & \
                 int(pm.get_device_info(id)[3] == 1):
             foundId = id
     return foundId
Esempio n. 13
0
 def __getDeviceId(self, midiport):
     n_device = pm.get_count()
     foundId = -1
     for id in range(n_device):
         if int(pm.get_device_info(id)[1] == midiport) & \
                 int(pm.get_device_info(id)[3] == 1):
             foundId = id
     return foundId
Esempio n. 14
0
 def get_info(self):
     l = []
     for x in range(pm.get_count()):
         l.append(pm.get_device_info(x))
         #dev = DeviceInfo(Index=x, info=pm.get_device_info(x))
         #self.dev_info[dev.type].add_child(existing_object=dev)
         #dev.bind(active=self.on_dev_info_active_set)
     return l
Esempio n. 15
0
def find_midi_device(device_name, direction):
    for index in range(midi.get_count()):
        _, name, is_input, is_output, _ = midi.get_device_info(index)
        name = name.decode("utf8")
        if name == device_name:
            if ((is_input and direction == "in") or
                (is_output and direction == "out")):
                return index
    raise UserError("Could not find {} device \"{}\"".format(direction.upper(), device_name))
Esempio n. 16
0
 def get_devices() -> DeviceList:
     from pygame import midi
     midi.init()
     names = [
         midi.get_device_info(x)[1].decode('ascii')
         for x in range(0, midi.get_count())
     ]
     midi.quit()
     return names
Esempio n. 17
0
def select_MIDI_out():
    """ Select and appropriate midi device"""
    midi_count =  midi.get_count()
    avail_devices = [midi.get_device_info(i) for i in range(midi_count)]
    print("Please select a MIDI device by selecting appropriate number")
    for num, device in enumerate(avail_devices):
        print("{}. {}".format(num, device))
    midi_choice = input("device id: ")
    return int(midi_choice)
Esempio n. 18
0
 def scan_midi_all_port(self):
     self.all_ports = []
     devnum = pmd.get_count()
     for i in range(devnum):
         dev = pmd.get_device_info(i)
         if dev[3] == 1:  # MIDI Output なら
             name = dev[1].decode()
             self.all_ports.append([i, name, False])
     return self.all_ports
Esempio n. 19
0
	def createInterfaces(self):
		"""
		creates all midi interfaces available as devices
		@todo: sort in- and output of one hardware
		"""
		n = midi.get_count()
		for i in xrange(n/2):
			info = midi.get_device_info(i*2)
			newIf = Interface(info[1], i*2-1, i*2)
Esempio n. 20
0
def find_id(target='Teensy MIDI'):
	init()
	for d in range( get_count() ):
		(interf, name, input, out, op) = get_device_info(d)
		name = str(object=name, encoding='utf-8')
		if (name == 'Teensy MIDI' and out == 1):
			return d
	quit()
	return None
Esempio n. 21
0
 def get_midi_output_id():
     for id in range(midi.get_count()):
         interface, name, input, output, open = midi.get_device_info(id)
         if not output:
             continue
         name = name.decode('utf-8').lower()
         if name.find('synth') != -1:
             return id
     return midi.get_default_output_id()
 def list_devices(self):
     for i in range(pm.get_count()):
         r = pm.get_device_info(i)
         (interf, name, input, output, opened) = r
         in_out = ""
         if input:
             in_out = "(input)"
         if output:
             in_out = "(output)"
         print ("%2i: interface :%s:, name :%s:, opened :%s: %s" % (i, interf, name, opened, in_out))
Esempio n. 23
0
 def GetPorts(self):
     i = {}
     o = {}
     for j in range(pm.get_count()):
         s, name, ins, outs, throughs = pm.get_device_info(j)
         if ins > 0:
             i[name] = j
         if outs > 0:
             o[name] = j
     return (i, o)
Esempio n. 24
0
def get_devices(name):
    id_in, id_out = None, None
    for i in range(midi.get_count()):
        info = midi.get_device_info(i)
        if info[1] == name:
            if info[2]:
                id_in = i
            elif info[3]:
                id_out = i
    return id_in, id_out
Esempio n. 25
0
def get_devices(name):
    id_in, id_out = None, None
    for i in range(midi.get_count()):
        info = midi.get_device_info(i)
        if info[1] == name:
            if info[2]:
                id_in = i
            elif info[3]:
                id_out = i
    return id_in, id_out
Esempio n. 26
0
 def GetPorts(self):
     i = {}
     o = {}
     for j in range(pm.get_count()):
         s,name,ins,outs,throughs = pm.get_device_info(j)
         if ins > 0:
             i[name] = j
         if outs > 0:
             o[name] = j
     return (i,o)
Esempio n. 27
0
def main():
	# Init midi lib
	Midi.init()

	done = False
	receivingSysEx = False
	sysExMsg = []

	device_count = Midi.get_count()
	#get info on devices
	if device_count > 0:
		print("Midi-devices found:")
		for device in range(device_count):
			temp = Midi.get_device_info(device) #get info on midi devices
			io = ""

			#Check if input or output
			if temp[2] and not temp[3]:
				io = "Input"
			elif temp[3] and not temp[2]:
				io = "Output"
			else:
				io = "Unrecognized"

			#Print info
			print(io, "Device #", device, temp[1])
	else:
		print("No Midi devices found \n exiting...")
		sys.exit(0) #No reason to carry on so exit

	#Prompt user for devices
	input_id = raw_input("Choose midi input device #: ")
	output_id = raw_input("Choose midi output device #: ")

	controller_id = raw_input("Choose midi controller: ")

	#Create handler
	tx7 = TX7(int(input_id),int(output_id))

	keyboard = MidiController(int(controller_id))

	#Change the first character to an 'A'
	#tx7.write_param(145,65)

	#Main loop. Currently no way to terminate!!! besides killing the process
	while not done:
		if tx7.poll():
			data = tx7.read()
			if data != 0:
				print(data)
		elif keyboard.poll():
			data = keyboard.read_noteMsg()
			if data != None:
				print(data)
				tx7.write_noteOn(data[1],data[2])
Esempio n. 28
0
    def output_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[3]):
                id = a
                if (self.mode != "live"):
                    id = a + 1
                return midi.Output(id)
        return False
 def list_devices(self):
     for i in range(pm.get_count()):
         r = pm.get_device_info(i)
         (interf, name, input, output, opened) = r
         in_out = ""
         if input:
             in_out = "(input)"
         if output:
             in_out = "(output)"
         print("%2i: interface :%s:, name :%s:, opened :%s: %s" %
               (i, interf, name, opened, in_out))
Esempio n. 30
0
def display_devices():
    '''
    Displays all available MIDI devices seen by mido
    '''
    midi = pygame.midi
    midi.init()
    print 'List of available MIDI devices:'
    print '(interf, name, input, output, opened)'
    for dev in xrange(0, midi.get_count()):
        print midi.get_device_info(dev)
    quit()
Esempio n. 31
0
    def get_devices():
        """Get a list of all MIDI output devices connected to the system."""

        if _midi is None:
            return
        outdevices = []
        all_ids = _midi.get_count()
        for device_id in all_ids:
            info = _midi.get_device_info(device_id)
            if info[3] == 1:
                outdevices.add([device_id, info[1]])
        return outdevices
Esempio n. 32
0
def _open_device(name='SSCOM MIDI 1', device_index=1):
    '''Opens midi device with given name and port number'''
    # This code stinks. Is there any better way to find the device?
    
    for dn in range(midi.get_count()):
        md = midi.get_device_info(dn)
        if (md[1] == name) and (md[3] == 1): # md[3] == 1 <=> output device
            device_index -= 1
            if device_index == 0:
                return midi.Output(dn)
        
    raise RuntimeError("Could not find a SoftStep Controller")
Esempio n. 33
0
    def devices(self):

        devices = []

        for i in range(midi.get_count()):

            driver, name, inp, outp, opened = midi.get_device_info(i)

            if outp:
                devices.append((i, driver, name, inp, outp))

        return devices
Esempio n. 34
0
 def connecter_sortie():
     ''' Appeler cette fonction pour récupérer une sortie MIDI.
     '''
     pgm.init(
     )  ### mettre le init ici va peut etre réler le bug sur le portable
     for ident in range(pgm.get_count()):
         info = pgm.get_device_info(ident)
         if info[3] == 1:  # c'est un output
             print("MIDI: Utilisation de", info[1])
             break
     #ident=pgm.get_default_output_id()
     return pgm.Output(ident)
Esempio n. 35
0
def create_initial_data(mox):
    pin = {}
    pout = {}
    for i in xrange(pym.get_count()):
        info = pym.get_device_info(i)
        name = info[1]
        if info[2]:
            pin[name] = i
        if info[3]:
            pout[name] = i
    
    return {"ports_in": pin, "ports_out": pout}
Esempio n. 36
0
def list_devices():
    for i in range(midi.get_count()):
        r = pygame.midi.get_device_info(i)
        (interf, name, input, output, opened) = r

        in_out = ""
        if input:
            in_out = "(input)"
        if output:
            in_out = "(output)"
        
        print("%i: %s %s" % (i, name, in_out))
Esempio n. 37
0
    def get_devices():
        """Get a list of all MIDI input devices connected to the system."""

        if _midi is None:
            return
        indevices = []
        all_ids = _midi.get_count()
        for device_id in all_ids:
            info = _midi.get_device_info(device_id)
            if info[2] == 1:
                indevices.add([device_id, info[1]])
        return indevices
Esempio n. 38
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"
Esempio n. 39
0
def construct_input(type='MK-449C USB MIDI Keyboard'):
	pm.init()
	n_device = pm.get_count()
	in_id = -1
	for id in range(n_device):
		if int(pm.get_device_info(id)[1]==type) & int(pm.get_device_info(id)[2]==1):
			in_id = id
			print "input: "+type
#	if in_id == -1:
#		print "desired input: "+type+ " not available"

	eingang = pm.Input(in_id)
	return eingang
Esempio n. 40
0
 def __init__(self):
     self.pin = {}
     self.pout = {}
     for i in xrange(pym.get_count()):
         info = pym.get_device_info(i)
         if info[2]:
             self.pin[i] = pym.Input(i)
         if info[3]:
             self.pout[i] = pym.Output(i)
             
     self.thread = threading.Thread(target=self._run)
     self.thread.daemon = True
     self.thread.start()
Esempio n. 41
0
 def __init__(self):
     self.input = None
     self.output = None
     self.config: dict[int, ChannelConfig] = {number: ChannelConfig() for number in range(16)}
     self.devices = []
     midi.init()
     try:
         for i in range(midi.get_count()):
             info = midi.get_device_info(i)
             self.devices.append(info)
     except Exception as e:
         self._end()
         raise e
Esempio n. 42
0
def detect_output_device():
    for i in range(pgm.get_count()):
        r = pgm.get_device_info(i)
        (interf, name, input, output, opened) = r

        if not output:
            continue

        if b'Midi Through' in name:
            continue

        print(f'Using output device #{i}: {name}')
        return i
Esempio n. 43
0
    def __init__(self, channel=1, device_id=None):
        super().__init__()
        self.output = None
        if not midi.get_init():
            midi.init()
        if device_id is None:
            device_id = midi.get_default_output_id()

        mididevs = {}
        dfldev = None
        for did in range(midi.get_count()):
            dev = midi.get_device_info(did)
            if dev[3] == 1:
                devname = dev[1].decode()
                mididevs[devname] = did
            if did == device_id:
                dfldev = devname

        def config_devbox(combo):
            def _set_dev_cb(c):
                self.set_device(self.device)

            combo.connect("changed", _set_dev_cb)
            self.set_device(self.device)

        self.setup_configurable(
            "MIDI Output",
            "midi",
            confmap={
                # "mode": ListConfiguration("Output Mode", "mode", default_val, items),
                "channel":
                NumericConfiguration(
                    "MIDI Channel",
                    "channel",
                    Gtk.SpinButton,
                    channel,
                    1,
                    16,
                    step_incr=1,
                    page_incr=1,
                ),
                "device":
                ListConfiguration(
                    "MIDI Device",
                    "device",
                    dfldev,
                    mididevs,
                    gui_setup_cb=config_devbox,
                ),
            },
        )
Esempio n. 44
0
    def get_input_devices(self):
        """
        Queries midi interface for available devices.
        Checks that they are input devices (third element in return tuple corresponds to input flag, 1 if input else 0).
        Returns a dict of the form {device_name: device_id}, device_id = -1 corresponds to no device.
        """
        input_devices = {}

        for i in range(midi.get_count()):
            if midi.get_device_info(i)[2] == 1:
                input_devices[midi.get_device_info(i)[1].decode('utf-8')] = i
        input_devices['None'] = -1

        return input_devices
Esempio n. 45
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(0.001)
     i = None
Esempio n. 46
0
def getMidiDevices():
    midiInputs = {}
    midiOutputs = {}

    for deviceNum in range(midi.get_count()):
        n, name, input, output, n = midi.get_device_info(deviceNum)

        if input:
            #Trim the name, getting rid of the byte prefix
            midiInputs[str(name)[2:-1]] = deviceNum
        if output:
            midiOutputs[str(name)[2:-1]] = deviceNum

    return midiInputs, midiOutputs
Esempio n. 47
0
 def refresh(self):
     self.children = SafeList()
     for index in xrange(midi.get_count()):
         info = midi.get_device_info(index)
         interf, name, input, output, opened = info
         if output <= 0:
             continue
         btn = MTToggleButton(label=name, size=(200, 30))
         btn.size = btn.label_obj.content_width + 20, 30
         btn.push_handlers(on_press=curry(self.select, index))
         self.add_widget(btn)
         if self.selected == index and \
             self.selectedname == name:
             btn.state = 'down'
Esempio n. 48
0
def construct_output(type='SimpleSynth virtual input',instrument=1):
# this constructs an output 
	pygame.init()
	pm.init()
	pm.init()
	n_device = pm.get_count()
	out_id = -1
	for id in range(n_device):
		if int(pm.get_device_info(id)[1]==type) & int(pm.get_device_info(id)[3]==1):
			out_id = id
			ausgang = pm.Output(out_id,0)
			ausgang.set_instrument(instrument)
			print "output: "+type
			return ausgang
	print "output: "+type+" not available"
Esempio n. 49
0
 def PrintOutputDevices():
     print("")
     print("Choose from the following:")
     for loop in range(pm.get_count()):
         interf,name,inp,outp,opened = pm.get_device_info(loop)
         if outp ==1:
             self.opts+=1
             if self.opts==1:
                     self.device=loop
             print(loop, name," (", interf, ") ", end="")
             if (opened == 1): print("(opened)")
             else: print("(unopened)")
     print("")
     if self.opts==0:
             print("No devices found!")
Esempio n. 50
0
def detect_input_device():
    for i in range(pgm.get_count()):
        r = pgm.get_device_info(i)
        (interf, name, input, output, opened) = r

        if not input:
            continue

        if b'Midi Through' in name:
            continue

        print(f'Using input device #{i}: {name}')
        return i

    raise Exception('MIDI input device not found')
Esempio n. 51
0
	def initApp(self):
		Midi.init()
		self.device_count = Midi.get_count()
		#Check if there are any midi devices
		if self.device_count > 0:
			#Spawn window
			self.pop_up = Pop_Up()
			self.connect(self, SIGNAL("lastWindowClosed()"), self.byebye)
			for device in range(self.device_count):
				self.temp = Midi.get_device_info(device)
				if self.temp[2] and not self.temp[3]:
					self.pop_up.addMidiInDevice(str(device) + " " + self.temp[1])
				elif self.temp[3] and not self.temp[2]:
					self.pop_up.addMidiOutDevice(str(device) + " " + self.temp[1])
		else:
			self.byebye()
Esempio n. 52
0
def init():
  global casio_input
  midi.init()
  piano_input_id = None
  for device_id in range(midi.get_count()):
    interf, name, input, output, opened = midi.get_device_info(device_id)
    if "CASIO" in name and input == 1:
      piano_input_id = device_id
      break

  if piano_input_id is None:
    return None
  else:
    print "Piano is connected on interface: " + str(piano_input_id)

  casio_input = midi.Input(piano_input_id)
Esempio n. 53
0
def _print_device_info():
    for i in range(get_count()):
        r = get_device_info(i)
        (interf, name, input, output, opened) = r

        in_out = ""
        if input:
            in_out = "(input)"
        if output:
            in_out = "(output)"

        print(
            "%2i: '%-19s', opened :%s:  %s"
            % (i, 
				str(name, encoding='utf-8'), opened, in_out)
        )
    def SearchDevices(self, name, output=True, input=True, quiet=True):
        ret = []
        i = 0
        for n in range(midi.get_count()):
            md = midi.get_device_info(n)
            if quiet == False:
                print(md)
                sys.stdout.flush()
            if string.find(md[1], name) >= 0:
                if output == True and md[3] > 0:
                    ret.append(i)
                if input == True and md[2] > 0:
                    ret.append(i)
            i += 1

        return ret
Esempio n. 55
0
 def get_devices(inputs=True, outputs=True):
     """
     Queries available devices. Returns list of pairs 
     C{(index,device_info)}. C{index} is the device number by which 
     it can be accessed. C{device_info} is a tuple in the same 
     format as C{pygame.midi.get_device_info()}:
     (interf, name, input, output, opened)
     
     """
     devices = [(num,pgmidi.get_device_info(num)) for num in range(pgmidi.get_count())]
     if inputs and not outputs:
         devices = [d for d in devices if d[1][2] == 1]
     elif outputs and not inputs:
         devices = [d for d in devices if d[1][3] == 1]
     elif not inputs and not outputs:
         return []
     return devices
Esempio n. 56
0
    def printDevices(self):
        inputs, outputs = list(), list()
        bad_devices = list()    # TODO: Dead code consider revising or adding items to catch
        for i in range(0, pm.get_count()):
            info = pm.get_device_info(i)
            if info[1] not in bad_devices:
                target = inputs if info[2] > 0 else outputs
                target.append((i, info[1]))

        # print list of input devices
        #print "Input devices: "
        #for i in range(len(inputs)):
        #    print inputs[i]

        # print list of output devices
        print "Output devices: "
        for i in range(len(outputs)):
            print outputs[i]
Esempio n. 57
0
def get_midi_devices():
	device_count = Midi.get_count()
	#get info on devices
	if device_count > 0:
		print("Midi-devices found:")
		for device in range(device_count):
			temp = Midi.get_device_info(device) #get info on midi devices
			io = ""

			#Check if input or output
			if temp[2] and not temp[3]:
				io = "Input"
			elif temp[3] and not temp[2]:
				io = "Output"
			else:
				io = "Unrecognized"

			#Print info
			print(io, "Device #", device, temp[1])
	else:
		print("No Midi devices found \n exiting...")
		sys.exit(0) #No reason to carry on so exit
Esempio n. 58
0
    def connect(self):
        """Connect to the first BBS-1"""
        logging.debug('Attempting MIDI connection')

        # Get number of MIDI devices
        devices = midi.get_count()

        # Search for the first BodyBeatSync input and output ports
        for i in range(0, devices):
            info = midi.get_device_info(i)
            # Name
            if re.match('.*BodyBeatSYNC.*', str(info[1])):
                # Input
                if info[2] >= 1:
                    dev_in = i
                # Output
                if info[3] >= 1:
                    dev_out = i

        # Let's check if we got something usable
        try:
            dev_in
        except NameError:
            error = "Couldn't find BodyBeatSync's input port"
            logging.warning(error)
            raise IOError(error)

        try:
            dev_out
        except NameError:
            error = "Couldn't find BodyBeatSync's output port"
            logging.warning(error)
            raise IOError(error)

        # Open input and output
        logging.debug('Opening MIDI ports')
        self.midi_in = midi.Input(dev_in)
        self.midi_out = midi.Output(dev_out)
Esempio n. 59
0
    def play(self, notes):
        notes.printinfo()
        # Choose an output device
        devices = []
        for i in range(midi.get_count()):
            info = midi.get_device_info(i)
            devices.append("{0}, {1}, Input:{2}, Output:{3}".format(info[0], info[1], info[2], info[3]))

        device = util.menu("Choose an output device", devices)
        out = midi.Output(device)

        # Translate notes into midi events
        print("Preprocessing")
        events = notes.toEvents()

        print("Playing")
        lastTime = 0
        on = 0
        off = 0
        for e in events:
            # Calculate relative time and convert to seconds
            ticks = e[0] - lastTime
            # This is not right yet
            seconds = notes.ticks_to_seconds(ticks)
            if e[3] is 'on':
                #out.update_time(e[0]-lastTime)
                time.sleep(seconds)
                lastTime = e[0]
                out.note_on(e[1], e[2], 0)
            elif e[3] is 'off':
                #out.update_time(e[0]-lastTime)
                time.sleep(seconds)
                lastTime = e[0]
                # Sometimes note_offs are lost?
                # Unbelievably sending twice reduces this.
                out.note_off(e[1], e[2], 0)
                out.note_off(e[1], e[2], 0)