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'])
def __init__(self, device, latency=None, buffer_size=None): """Create a MIDI output. Parameters ---------- device : int or str id or name of the MIDI device latency : int, optional delay in ms applied to timestamp buffer_size : int, optional number of events to be buffered """ import types if type(_midi) is not types.ModuleType: raise ImportError("""Sorry, MIDI output is not supported on this computer.""") if not expyriment._active_exp.is_initialized: raise RuntimeError( "Cannot create MidiOut before expyriment.initialize()!") _midi.init() Output.__init__(self) self._id = device if buffer_size is None: buffer_size = defaults.midiout_buffer_size self._buffer_size = buffer_size if latency is None: latency = defaults.midiout_latency self._latency = latency self.output = _midi.Output(device, latency, buffer_size)
def __init__(self): self.b = [] self.enumerate_devices() self.init_audio() self.reset_strip() self.history=collections.deque() self.lpf_audio=[0]*len(self.RANGES) self.dt=float(self.CHUNK)/self.RATE self.alpha=self.dt/(self.TAU_LPF+self.dt) self.hue=0. self.stepfns = [self.step] self.smooth_dict = {} self.mute_delta = 0 self.mute = 1.0 self.whiteout_delta = 0 self.whiteout = 1.0 midi.init() self.mi = None try: self.mi = midi.Input(3) except: traceback.print_exc() print "Can't find midi. Continuing..." self.mstat = {} self.hueoff = 0 super(Visualizer, self).__init__()
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'])
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)
def get_device(device_id): midi.init() keys = ['interface', 'name', 'is_input', 'is_output', 'opened'] info = dict(zip(keys, midi.get_device_info(device_id))) info['device_id'] = device_id return info
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 main(): fin = open("workfile2.txt",'r') midi.init() p1 = midi.Output(2) instrument = 0 count = 0 while (count < 50): line = parse(fin) x = line[0] v = line[1] if (line[-1] == 'fist'): instrument = 41 elif (line[-1] == 'wave_out'): instrument = 31 elif (line[-1] == 'rest'): instrument = 1 elif (line[-1] == 'wave_in'): instrument = 59 else: intrument = 67 p1.set_instrument(instrument) print line NOTE = 64.0 + 64.0*x VOLUME = 64.0 + 64.0*v p1.note_on(int(NOTE),int(VOLUME)) time.sleep(0.25) p1.note_off(int(NOTE),int(VOLUME)) count += 1 del p1 midi.quit() fin.close()
def __init__(self, device, latency=0, buffer_size=1024): """Create a MIDI output. Parameters ---------- device : int or str id or name of the MIDI device latency : int, optional delay in ms applied to timestamp (default=0) buffer_size : int, optional number of events to be buffered (default=1024) """ if not isinstance(_midi,ModuleType): raise ImportError("""Sorry, MIDI output is not supported on this computer.""") if not _internals.active_exp.is_initialized: raise RuntimeError( "Cannot create MidiOut before expyriment.initialize()!") _midi.init() Output.__init__(self) self._id = device self._buffer_size = buffer_size self._latency = latency self.output = _midi.Output(device, latency, buffer_size)
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)
def main(): midi.init() pygame.init() app = QtWidgets.QApplication(sys.argv) form = QueryByLickMainWindow() form.show() app.exec_()
def __enter__(self): print "entering DeviceSource" print " initializing MIDI interface" midi.init() print " acquiring MIDI input" self.midi_input = midi.Input(self.midi_id) print " acquiring video input" self.video_input = cv2.VideoCapture(self.video_id) return self
def play_chords(chords): midi.init() out = init_output_device() for ns in chords: print ns play_chord(out, ns) out.close() out.abort() try: midi.quit() except: pass
def init(text='HELO', device_index=1): '''Finds and initializes the device''' global softstep midi.init() softstep = _open_device('SSCOM MIDI 1', device_index) _standalone(False) display(text) reset_leds()
def __init__(self, name): super(MidiDevice, self).__init__() # Initialize the python midi module midi.init() # Get the Midi device that we want to control self.outport = self.get_device(name) # True/False whether to play or now self.play = True # List of notes currently being played self.playing_notes = [] #Each element is of the form: [note, velocity, duration] self.playing_mutex = threading.Lock()
def __init__(self, name, n_read=100): pm.init() self.nread = n_read id = self.__getDeviceId(name) if id == -1: print "SETUP WARNING!!! input: " + name + " not available!!!" return None else: super(InputDevice,self).__init__(id) print "SETUP input: " + name + " connected with id", id
def run(self): pm.init() self.running.set() while self.running.isSet(): if len(self.active_inputs): flag = self.active.wait(self.input_poll_time) else: flag = self.active.wait() if self.running.isSet(): self.do_next_item() if not flag: self.check_inputs()
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 run(self): try: self.running = True midi.init() self.runthread() except: raise finally: if self.out: self.notesoff() self.out.close() midi.quit() self.running = False
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
def main(): Midi.init() done = False get_midi_devices() #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: ") pygame.init() screen = pygame.display.set_mode(SIZE) pygame.display.set_caption("TX7 test") #Create handlers tx7 = TX7(int(input_id),int(output_id)) keyboard = MidiController(int(controller_id)) #Clock control. clock = pygame.time.Clock() #Main loop while not done: #Handle keyboard for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: done = True if tx7.poll(): #Data from TX7 takes priority 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]) text = "FPS: {0:2f}".format(clock.get_fps()) pygame.display.set_caption(text) clock.tick(FPS) #proper exit pygame.quit() sys.exit(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
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"
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)
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()
def __init__(self, outputs, pars, neuron2NoteConversion=4): self.pars = pars super(OutputHandler, self).__init__() self.display = Display(pars['N_col'], pars['N_row'],\ ['Ne', 'Ni', 's_e', 's_i', 'tau_e', 'tau_i', 'midi_ext_e', 'midi_ext_i', 'cam_ext', 'cam_external_max'], 'lines', screenSize=pars['screen_size']) pm.init() self.__output = outputs if Visuals.NAME in self.__output: self.__output[Visuals.NAME].note_on(1) # self.__membraneViewer = Test() self.__now = time.time() self.__activeNotes = set() self.__neuron2NoteConversion = neuron2NoteConversion
def main(): pygame.init() midi.init() default_input_device = midi.get_default_input_id() default_output_device = midi.get_default_output_id() if default_input_device < 0: print "No MIDI input device found" return melodies = [] keyboard = ChordBuilderKeyBoard(default_input_device, melodies, output_device_id=default_output_device) print "Initialized" keyboard.start()
def __init__(self, data, master=None): Treeview.__init__(self, master=master, columns=["friendly_name", "status"]) self.data = data self.heading("#0", text="Port", anchor="w") self.column("#0", width = 150) self.heading("friendly_name", text="Name", anchor="w") self.column("friendly_name", width = 250) self.heading("status", text="Status", anchor="w") self.column("status", width = 100) self.bind("<<TreeviewSelect>>", self.update_status_button) midi.init() self.populate_list() self.pack(fill="both", expand="yes")
def main(): # Initialize Pygame midi subsystem midi.init() # Register our handler which translates midi notes to keybaord keys midihandlers.register_note_to_key(note_to_key) # Listen on every MIDI input found on system for pos, info in midihandlers.get_inputs(midi): try: (interf, name, input, output, opened) = info print 'Listening on', name # Run event listener for this input in its own thread midihandlers.run_threaded(midi.Input(pos)) except Exception as e: print e raw_input('Press enter to exit')
def __init__(self, tracks, bpm=120, resolution=8): self.running = False self.condition = threading.Condition() self.mode = self.STOPPED self.out = None self.on = [] self.tracks = tracks self.resolution = resolution self.bpm = bpm self.command_queue = deque() midi.init() threading.Thread.__init__(self)
def main(self): # initiate the parser parser = argparse.ArgumentParser() parser.add_argument("-si", "--serial-input", help="set serial input port (eg: /dev/tty)") parser.add_argument("-so", "--serial-output", help="set serial output port (eg: /dev/tty)") parser.add_argument("-m", "--midi", help="set midi output device (eg: 0)", type=int) parser.add_argument( "-l", "--list-ports", help="show serial ports and MIDI devices available and exit", action="store_true") # read arguments from the command line args = parser.parse_args() if args.list_ports: self.list_ports() parser.exit() if not args.serial_output and args.midi == None: print("Error: Serial port or MIDI device is missing.\n") self.list_ports() parser.exit() if args.serial_output and args.midi != None: print("Error: Must only specify Serial or MIDI.") parser.exit() self.serial_input_available = False if args.serial_input: self.serial_input_available = True if args.serial_output or args.serial_input: self.mode = Game.MODE_SERIAL # serial init self.bps = 2000000 self.port = args.serial_output or args.serial_input self.ser = serial.Serial(self.port, self.bps, timeout=1) if args.midi != None: self.mode = Game.MODE_MIDI # midi init midi.init() self.port = int(args.midi) self.midi = midi.Output(self.port, latency=0, buffer_size=0) # for use with notes self.octave = 4 self.channel = 1 self.notes = [] self.pressed_notes = [] self.pressed_notes_text = [] self.released_notes = [] self.pixels_to_move_keyboard = 0 # pygame init display.init() font.init() display_info = display.Info() Screen.monitor_rect.size = (display_info.current_w, display_info.current_h) self.fullscreen = INITIAL_FULLSCREEN_MODE if self.fullscreen: self.real_window = display.set_mode(Screen.monitor_rect.size, FULLSCREEN, BIT_DEPTH) else: self.real_window = display.set_mode(Screen.window_rect.size, WINDOWED + RESIZABLE, BIT_DEPTH) self.window = surface.Surface(VIEWPORT_SIZE) # clock clock = time.Clock() # fonts self.key_font = font.SysFont("monospace", 8, bold=True) self.osd_font = font.SysFont("monospace", 14) self.title_font = font.SysFont("monospace", 24) # @800x600, max 56 chars self.big_font = font.SysFont("monospace", 50, bold=True) # pseudo message box self.special_message = None self.text_message = None self.current_char = "" # init pseudo message box depending on mode if self.mode == Game.MODE_SERIAL: self.device_name = Message("Serial port %s" % self.port) if self.mode == Game.MODE_MIDI: self.device_name = Message("MIDI port %s" % self.port) # keyboard drawing previous_white_note = KeyboardNote(KeyboardNote.WHITE_KEY) previous_white_note.pos.x = (-previous_white_note.pos.width - 1) * 24 previous_white_note.pos.bottom = self.window.get_rect().bottom - 2 black_keys = [] white_keys = [] for note in range(MIN_NOTE, MAX_NOTE + 1): n = note % 12 if n == 1 or n == 3 or n == 6 or n == 8 or n == 10: new_note = KeyboardNote(KeyboardNote.BLACK_KEY, note) x_movement = -new_note.pos.width / 2 + 1 else: new_note = KeyboardNote(KeyboardNote.WHITE_KEY, note) x_movement = 1 new_note.pos.topleft = previous_white_note.pos.topright new_note.pos.x += x_movement previous_note = new_note if n == 1 or n == 3 or n == 6 or n == 8 or n == 10: black_keys.append(new_note) else: previous_white_note = new_note white_keys.append(new_note) # union of notes with black keys at the end so they get drawn on top self.notes = white_keys + black_keys # background bg = surface.Surface(VIEWPORT_SIZE) bg.fill(Colors.BLACK) self.window.blit(bg, RECT_INIT) # main cycle while True: # time clock.tick(60) self.handle_game() # debug fps if DEBUG: text_ticks = self.osd_font.render( "delta time: %04d ms" % (clock.get_rawtime()), NOALIAS, Colors.WHITE) self.window.blit(text_ticks, (5, 5)) if clock.get_fps() > 0: text_fps = self.osd_font.render( "fps: %d (~%.2f ms)" % (clock.get_fps(), clock.get_time()), NOALIAS, Colors.WHITE) self.window.blit(text_fps, (5, 20)) # update window if self.fullscreen: transform.scale(self.window, Screen.monitor_rect.size, self.real_window) else: transform.smoothscale(self.window, Screen.window_rect.size, self.real_window) display.update()
class CM_ND_MidiInitNode(bpy.types.Node, CM_ND_BaseNode): bl_idname = "cm_audio_midi_init_node" bl_label = "MIDI RealTime Data" bl_width_default = 150 """Access MIDI Data from One or Two Controllers""" is_pygame_init: BoolProperty(name = "MIDI Input", default=True) num_packets : IntProperty(name="Packets", default=1,min=1) pgm.init() num_packets = 1 midi_input = None midi_input2 = None mid_1_valid = True mid_dev_num = pgm.get_count() if mid_dev_num == 1: midi_info1 = str(pgm.get_device_info(0)) if midi_info1.split(',')[2].strip() == '1': midi_input = pgm.Input(0) else: # Reduce mid_dev_num by 1 - this will now be 0 and trapped in the execute function mid_dev_num = mid_dev_num - 1 elif mid_dev_num == 2: midi_info1 = str(pgm.get_device_info(0)) midi_info2 = str(pgm.get_device_info(1)) if midi_info1.split(',')[2].strip() == '1': midi_input = pgm.Input(0) else: # Reduce mid_dev_num by 1 and set midi_input 1 to invalid mid_dev_num = mid_dev_num - 1 mid_1_valid = False if midi_info2.split(',')[2].strip() == '1': if mid_1_valid: # Set second midi_input to this pygame input midi_input2 = pgm.Input(1) else: # Set first midi_input to this pygame input (only this is valid) midi_input = pgm.Input(1) else: # Reduce mid_dev_num by 1 mid_dev_num = mid_dev_num - 1 else: # We only handle up to 2 interfaces for now message = 'None or More than 2, MIDI Interface(s)' # By now we should have a number for valid Midi Inputs def init(self, context): super().init(context) self.outputs.new("cm_socket.midi", "Midi Data") def draw_buttons(self, context, layout): cm_pg = context.scene.cm_pg layout.prop(self, "is_pygame_init") layout.prop(self, "num_packets") def get_midi(self): buffer1 = [] buffer2 = [] cm = bpy.context.scene.cm_pg if self.is_pygame_init and self.midi_input is not None: # messages are formatted this way: [[message type, note / parameter ID, velocity # / parameter value, ?], TimeStamp] buffer1 = pgm.Input.read(self.midi_input, self.num_packets) if len(buffer1) > 0: cm.midi_buffer["buffer1"] = [b[0] for b in buffer1] if cm.midi_debug: print('Dev 1: ' + str(pgm.get_device_info(0))) print(str(cm.midi_buffer["buffer1"])) if self.midi_input2 is not None: buffer2 = pgm.Input.read(self.midi_input2, self.num_packets) if len(buffer2) > 0: cm.midi_buffer["buffer2"] = [b[0] for b in buffer2] if cm.midi_debug: print('Dev 2: ' + str(pgm.get_device_info(1))) print(str(cm.midi_buffer["buffer2"])) return [cm.midi_buffer["buffer1"], cm.midi_buffer["buffer2"]] else: return None def output(self): return self.get_midi()
def get_devices(**kwargs): midi.init() return [_get_device(device_id) for device_id in range(midi.get_count())]
def main(): pygame.init() midi.init() devNum = -1 for m in range(midi.get_count()): device = midi.get_device_info(m) print(device, device[1], device[2]) if "AKM320" in str(device[1]) and device[2] == 1: devNum = m print(devNum) if devNum == -1: print("Keyboard not found") sys.exit(1) screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Keytar Hero") clock = pygame.time.Clock() inp = midi.Input(devNum) keyStarts = [] for i in range(5): keyStarts.append(80 + i * 100) keyHitBoxes = [] for x in keyStarts: keyHitBoxes.append(pygame.Rect((x, 400, 50, 50))) activeNotes = [] pressedKeys = [] while True: clock.tick(60) r = randint(1, 20) if r == 10: r2 = randint(0, 4) activeNotes.append(pygame.Rect((80 + r2 * 100, 0, 50, 50))) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) # clear the screen screen.fill((0, 0, 0)) if inp.poll(): keys = inp.read(1000) keys = sorted(keys, key=getKeySorter) keys = sorted(keys, key=getKeySorter1) print(keys) for key in keys: try: if key[0][0] == KEY_ON: pressedKeys.append(key[0][1]) elif key[0][0] == KEY_OFF: pressedKeys = removeAll(pressedKeys, key[0][1]) cheatMap[key[0][1]] = 0 except ValueError as e: print("Error key: " + str(key[0][1])) else: pass finally: pass print(pressedKeys) for rect in keyHitBoxes: pygame.draw.rect(screen, (255, 255, 255), rect) # remove overlapping random notes for note in activeNotes: index = note.collidelist(activeNotes) if index != -1 and note != activeNotes[index]: activeNotes.remove(activeNotes[index]) # check if notes need to be pressed for note in activeNotes: index = note.collidelist(keyHitBoxes) if index != -1: noteThatNeedsToBePressed = keyMap[note.left] if noteThatNeedsToBePressed in pressedKeys: activeNotes.remove(note) cheatMap[noteThatNeedsToBePressed] += 1 if cheatMap[noteThatNeedsToBePressed] >= 3: print("cheating") ser.write(b'2') hitNote() # move notes down screen and remove them if they are missed for note in activeNotes: note.top += 3 if note.top >= 480: activeNotes.remove(note) missNote() else: pygame.draw.rect(screen, keyColorMap[note.left], note) # # update the screen pygame.display.flip()
def midi_inited(): midi.init() try: yield finally: midi.quit()
ID = self.midi_outs[name] print name, ID self.midi_handler.connect_Output(ID) def GenerateMapping(self): l = {} for i in self.controllers: i.UpdateMapping() class myFrame(wx.Frame): def __init__(self, title='title', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, None, title=title, size=size, style=style) self.midi_handler = Midi(self) self.panel = myPanel(self, self.midi_handler) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) def OnCloseWindow(self, event): self.Destroy() pm.init() app = wx.App() top = myFrame() top.Show() app.MainLoop()
def MidiInit(): # pygame inits mixer.pre_init(44100, -16, 2, 256) mixer.init() midi.init() # wypisywanie listy urządzeń wejściowych input_devices = [-1] print('[0] Klawiatura') for x in range(midi.get_count()): dev_info = midi.get_device_info(x) if dev_info[2] == 1: input_devices.append(x) print('[{}]'.format(len(input_devices) - 1), dev_info[1].decode('utf-8')) default_device = len(input_devices) - 1 # wybieranie urządzenia wejściowego try: dev = int( input("Wybierz urządzenie wejściowe [" + str(default_device) + "]: ")) except ValueError: dev = default_device if dev >= len(input_devices) or dev < 0: print('Nieprawidłowy numer urządzenia! Wybrano domyślne.') dev = default_device # inicjalizacja urzadzenia inputs = [] dev_nr = input_devices[dev] if dev_nr == -1: inputs.append(KeyboardInput()) inputs[0].start() else: inputs.append(midi.Input(dev_nr)) # wypisywanie dostępnych sampli dirlist = listdir('./samples') samples = [] for dirname in dirlist: if path.isdir('./samples/' + dirname): samples.append(dirname) print('[{}]'.format(len(samples) - 1), dirname) default_samples = len(samples) - 1 # wybieranie sampli try: samples_nr = int( input("Wybierz sample dźwiękowe [" + str(default_samples) + "]: ")) except ValueError: samples_nr = default_samples if samples_nr >= len(samples) or samples_nr < 0: samples_nr = default_samples samples_path = './samples/' + samples[samples_nr] # inicjalizacja plików dźwiękowych sounds = [{}, {}] for sample_name in listdir(samples_path): name, ext = path.splitext(sample_name) if ext == '.wav': try: it = int(name) except: continue sounds[0][it] = mixer.Sound(samples_path + '/' + sample_name) sounds[1][it] = mixer.Sound(sounds[0][it]) # określanie pozostałych ustawień try: sustain = int(input('Podaj wartość sustain [200]: ')) except ValueError: sustain = 200 try: channels = int( input('Podaj ilość kanałów dźwiękowych [' + str(32) + ']: ')) except ValueError: channels = 32 mixer.set_num_channels(channels) return inputs, sounds, sustain
def get_devices(): midi.init() return [get_device() for device_id in range(midi.get_count())]
""" N_SCENE = 9 channel_name_tab = {} for i in range(N_SCENE) : channel_name_tab[16+i] = 'knob_'+str(i) for i in range(N_SCENE) : channel_name_tab[i] = 'slider_'+str(i) for i in range(N_SCENE) : channel_name_tab[32+i] = 's_button_'+str(i) for i in range(N_SCENE) : channel_name_tab[48+i] = 'm_button_'+str(i) for i in range(N_SCENE) : channel_name_tab[64+i] = 'r_button_'+str(i) print channel_name_tab """ #---------------------------------------------------------------------------- # midi init midi.init() print "Devices ID : "+ str(midi.get_default_input_id()) print "Devices Info : "+ str(midi.get_device_info(midi.get_default_input_id())) if (midi.get_default_input_id() == -1): print("exit") exit(-1) INDEX_STATUS = 0 INDEX_CHANNEL = 1 INDEX_VALUE = 2 buffer_size = 200 controller = midi.Input(midi.get_default_input_id(),buffer_size) # In case there are more than MIDI controller #controller = midi.Input(3 ,buffer_size)
def Setup(): print("[" + time.strftime("%H:%M:%S", time.localtime()) + "]", end = " ") print("Program started") #First we read the config to correctly define our global variables global setup_json try: #This allows us to either put the config name in the argv variables or to get asked for the config #Example: python ProgramName.py ConfigName if len(sys.argv) > 1: Filename = sys.argv[1] else: Filename = input("What is the name of your config file?") if Filename == "": Filename = "FrequenceBanane" #Open the config JSON setup_json = json.loads(''.join(open("Config\\" + Filename + ".json", "r"))) print("Opened config: " + Filename) #Define the global config variables correctly if "config_general" in setup_json: config_general = setup_json["config_general"] if "ConfigName" in config_general: global ConfigName ConfigName = config_general["ConfigName"] else: print("ERROR 404: ConfigName argument was not found") if "StudioMode" in config_general: global StudioMode StudioMode = config_general["StudioMode"] else: print("ERROR 404: StudioMode argument was not found") if "DefaultTransition" in config_general: global DefaultTransition DefaultTransition = config_general["DefaultTransition"] else: print("ERROR 404: DefaultTransition argument was not found") if "DefaultTransitionDuration" in config_general: global DefaultTransitionDuration DefaultTransitionDuration = config_general["DefaultTransitionDuration"] else: print("ERROR 404: DefaultTransitionDuration argument was not found") if "server_ip" in config_general: global server_ip server_ip = config_general["server_ip"] else: print("ERROR 404: server_ip argument was not found") if "server_port" in config_general: global server_port server_port = config_general["server_port"] else: print("ERROR 404: server_port argument as not found") if "server_password" in config_general: global server_password server_password = config_general["server_password"] else: print("ERROR 404 server_password argument was not found") else: print("No general config in config file") except FileNotFoundError: print("Config file " + Filename + " not found") #Here we connect to the OBS Websocket global ws try: ws = obsws(server_ip, server_port, server_password) ws.connect() print("Connected to Websocket") except: print("Connection to OBS Websocket is impossible") print("Exiting program") exit() #Here we connect to the midi pad global midi_in global midi_out try: midi.init() midi_in = midi.Input(1, 1024) midi_out = midi.Output(3, 1024) print("Connected Midi Pad") except: print("Midi Pad not found") print("Chaque année, des millions de programmeurs disent qu'ils vont régler ce problème, et ils ne le font jamais. Si vous voyez ce message, c'est que nous faisons parti de ces programmeurs.") print("Exiting program") exit() print("[" + time.strftime("%H:%M:%S", time.localtime()) + "]", end = " ") print("Program is ready to use")
def __init__(self,midi_id=1): threading.Thread.__init__(self) midi.init() self.input = midi.Input(midi_id)
def init_midi(): pygame.init() midi.init()
#!/usr/bin/env PYTHON3 import mido import pygame.midi as pym import tkinter as tk import random import threading from tkinter import messagebox from time import sleep from timeit import default_timer as dtime mido.set_backend('mido.backends.pygame') pym.init() class Switcher: # manages state def __init__(self): self.run_state = False def switch_on(self): self.run_state = True def switch_off(self): self.run_state = False class Interface( tk.Frame ): # Creates the app's GUI and initiates processing through generate_output method def __init__(self, switch, master=None):
__revision__ = '' __date__ = '' from types import ModuleType, FunctionType from expyriment import _internals from expyriment._internals import CallbackQuitEvent from expyriment.misc._timer import get_time from expyriment.io._keyboard import Keyboard from expyriment.io._input_output import Input import time try: from pygame import midi as _midi _midi.init() except: _midi = None class MidiIn(Input): """A class implementing a MIDI input. **EXPERIMENTAL!** Due to a bug in Pygame's midi module, closing a MidiIn (or the programme) will cause an error message. Until this is fixed in Pygame, MidiIn will stay in extras. """
def refresh(self): pm.init()
def init(self): pm.init() # Init Pygame Midi Module # Creation of the midi out object self.midi_output = pm.Output(_MIDI_OUT_DEVICE_ID)