Ejemplo n.º 1
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()
Ejemplo n.º 2
0
    def run(self):
        self.running = True
        self.isAlive = True
        try:
            while True:
                if not self.running:
                    break
                while self.input.poll():
                    packet = self.input.read(1)
                    status = packet[0][0][0]
                    knob = packet[0][0][1]
                    value = packet[0][0][2]
                    print knob
                    if status==144:
                        pass
                        #self.kill_callback()

                    print "Knob: %d Value: %d , Status: %d" % (knob,value,status)
                    if knob in self.callbacks:
                        self.callbacks[knob](value)
                time.sleep(.01)
        except KeyboardInterrupt as e:
            print "MidiInput caught interrupt"
            threading.interrupt_main()
        print "Input threading quitting"
        self.isAlive = False
        midi.quit()
        sys.exit(0)
Ejemplo n.º 3
0
def endthis(a, b):
    if tc != None:
        print "Closing device"
        tc.close()
        pm.quit()

    sys.exit(0)
Ejemplo n.º 4
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()
def autorecord(k, name):  #k number of recordings
    #needs 15.5 gb total
    #per sample runtime = 3.8 sec
    i = 1
    #Create player 101
    #k is from 2 to 590
    #j is 1 to 50

    time.sleep(5)
    while i <= k:
        #tic=time.time()
        p = pyaudio.PyAudio()  # Create an interface to PortAudio
        j = 2 + ((i - 1) // 50)
        filename = 'User' + str(j) + 'Aug' + str(i - 50 * ((i - 1) // 50))
        soundarray = record(filename, p)
        savewav(filename, soundarray, p)
        keyboard.press('n')
        keyboard.release('n')
        time.sleep(0.5)
        keyboard.press(Key.down)
        keyboard.release(Key.down)
        time.sleep(0.1)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
        i = i + 1
        p.terminate()
        del p
        time.sleep(0.5)
        #elapsedtime=time.time() -tic

    pgm.quit()
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
 def _end(self):
     if self.input is not None:
         self.input.close()
         self.input = None
     if self.output is not None:
         self.output.close()
         self.output = None
     midi.quit()
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def handler(signal, frame):
    try:
        # Close and quit everything on CTRL+C
        midi.close()
        pymidi.quit()
        pymix.quit()
        pygame.quit()
    except Exception:
        pass

    sys.exit(0)
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
 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
Ejemplo n.º 15
0
def kickit():
	port = find_id()
	if (port):
		print("kick on", device_name(port))
		midi_out = Output(port, 0)
		# Midi raw channel 9 is percussion, most people call it channel 10
		# pygame passes channel number verbatim
		midi_out.note_on(36, 101, channel=9)
		sleep(0.05)
		midi_out.note_off(36, channel=9)
		quit()
	else:
		print("no teensy MIDI available")
Ejemplo n.º 16
0
def cleanExit(signal=None, frame=None):
    # Probably pressed Ctrl-C, try to gracefully exit.
    # Wait for already playing notes to complete
    global stopping
    if not stopping:
        stopping = True
        if drum:
            beatTimer.cancel()
        for thread in list(activeNotes):
            if thread.is_alive():
                thread.join()
        midiOut.close()
        midi.quit()
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
        def run(self):
            t=0

            if self.verbose:
                class report():pass
                rpt=report()
                rpt.sleeps=0
                rpt.latencies=[]

            try:
                while (not self.stop) or (self.incoming!=[] and not(self.incoming.empty())):

                    while pm.time()<=t:
                        if self.verbose: rpt.sleeps+=1
                        time.sleep(.0003) #prevent proc hog - is this too small to actually sleep?  don't want to miss transition to next millisecond...

                    t=pm.time()

                    while (not self.immediately) and self.incoming.queue!=[] and t>=self.incoming.queue[0][0]-self.appLatency: #accessing incoming.queue epends on private implementation of queue.PriorityQueue, hack cuz no peek method provided
                                                                                                    #note a technical concurrency bug here -- queue may become [] after checking for that and before asking for queue[0][0], but since this is the only consumer, shouldn't happen
                            try:
                                    s,e=self.incoming.get_nowait()
                                    if self.verbose: rpt.latencies.append(s-t)
                                    self.MidiOut.write(e)
                            except queue.Empty:
                                    if self.verbose: print("non empty queue throwing empties")
                                    break
            finally:
                if self.immediately:
                    def allNotesOff(m):
                        for i in range(NUM_MIDI_CHANS):
                            for j in range(MIDI_MAX):
                                m.write([[[NOTE_ON + i,j,0],0]])
                    allNotesOff(self.MidiOut)
                if self.verbose and len(rpt.latencies)>0:
                    #print("sleeps: " + str(rpt.sleeps))
                    misses=len(list(filter(lambda x:x<0,rpt.latencies)))
                    def mean(x):
                        return sum(x)/len(x)
                    def std(x):
                        m=mean(x)
                        return mean(list(map(lambda y:abs(y-m),x)))
                    print("latencies (ms, negative=late): mean=" + str(mean(rpt.latencies)) + " std=" + str(std(rpt.latencies)) + " misses=" + str(misses) + " of " + str(len(rpt.latencies)) + " (" + str(100*misses/len(rpt.latencies)) +"%)")
                del self.MidiOut
                pm.quit()
Ejemplo n.º 19
0
def listen_to(device_ids):
    try:
        devices = [midi.Input(device_id) for device_id in device_ids]
        while True:
            for device in devices:
                if device.poll():
                    events = device.read(NUM_EVENTS)
                    for event in events:  # e.g.: [[[137, 41, 0, 0], 1373474], [[153, 41, 8, 0], 1373475], ...]
                        data, timestamp = event
                        _, note_number, _, _ = data
                        if note_number in FREEDRUM:
                            keyboard.press_and_release(FREEDRUM[note_number])
            sleep(SLEEP_TIME_IN_SECS)  # Prevent busy polling at 100% CPU.
    except KeyboardInterrupt:
        print('\nInterrupted. Shutting down...')
    finally:
        for device in devices:
            try_close(device)
        midi.quit()
        print('Bye!')
Ejemplo n.º 20
0
    def onRecord(self, e):
        """"""
        if self.recordButton.GetLabel() == "&Stop":
            self.recordButton.SetLabel("&Record")
            self.recordButton.Disable()
            self.going = False
            self.makeSong()
        else:
            if self.recordButton.GetLabel() == "&Record":
                self.recordButton.SetLabel("&Stop")
            midiIn = Input(midi.get_default_input_id())

            self.processKey()

            self.write("Getting input from:")
            self.write(midi.get_device_info(midi.get_default_input_id()))

            event_get = pygame.fastevent.get
            event_post = pygame.fastevent.post
            self.going = True
            startTime = time.time()
            try:
                while self.going and (time.time() - startTime) <= 20:
                    events = event_get()
                    for e in events:
                        if e.type in [QUIT]:
                            self.going = False
                    if midiIn.poll():
                        midiEvents = midiIn.read(10)
                        #                        self.write( midiEvents)
                        for m in midiEvents:
                            if m[0][1] > 0 and m[0][2] > 0:
                                self.write("Read note:" + str(self.notes[(m[0][1] + 3) % 12]))
                                self.tune.append(m[0][1])
                        midiEvs = midi.midis2events(midiEvents, midiIn.device_id)
                        for mE in midiEvs:
                            #                            self.write( "mE = ", mE)
                            event_post(mE)
            finally:
                del midiIn
                midi.quit()
Ejemplo n.º 21
0
def loop():
    global pad_in
    global pad_out
    global fastmode
    control(0, 1)
    for i in range(8):
        for j in range(8):
            if (i + j) % 2 == 0:
                note_on([i, j], [0, 3])
    control(1, 0)
    for i in range(8):
        for j in range(8):
            if (i + j) % 2 == 1:
                note_on([i, j], [3, 0])
    delay = 60.0 / bpm
    count = 1
    if skip:
        beat = 8
    else:
        beat = 1
        count = 1.2
    state = True
    while pad_in.poll():
        pad_in.read(2)
    if not fastmode:
        raw_input("press enter to start")
    while True:
        if pad_in.poll():
            break
        if count % beat != 0:
            state = swap(state)
        count += 1
        time.sleep(delay)

    send_signal(176, 0, 48)
    reset()
    del pad_in
    del pad_out
    midi.quit()
    sys.exit(0)
Ejemplo n.º 22
0
 def playSong(self, e):
     """"""
     midi.init()
     O = Output(midi.get_default_output_id())
     onNotes = []
     notes = []
     for y in range(len(self.myChords)):
         self.myChords[y] = [x + 36 for x in self.myChords[y]]
     for i in range(len(self.myNotes)):
         notes.append(self.myChords[i] + [(self.myNotes[i])])
     rhythms = self.myRhythm
     for i in range(len(self.myNotes)):
         for k in notes[i]:
             if k not in onNotes:
                 O.note_on(k, 127)
                 onNotes.append(k)
         time.sleep(rhythms[2 * i + 1] - rhythms[2 * i])
         for k in notes[i]:
             if k in onNotes:
                 onNotes.remove(k)
                 O.note_off(k)
     self.pop = wx.POPUP_WINDOW(self, name="Test")
     del O
     midi.quit()
Ejemplo n.º 23
0
def midi_inited():
    midi.init()
    try:
        yield
    finally:
        midi.quit()
Ejemplo n.º 24
0
 def __del__(self):
     if midi:
         midi.quit()
Ejemplo n.º 25
0
def handler(signum, frame):
    pymidi.quit()
    pygame.quit()
Ejemplo n.º 26
0
 def quit(self):
     midi.quit()
Ejemplo n.º 27
0
def del_out():
    midi.quit()
    del midi_out
Ejemplo n.º 28
0
import pygame.midi as midi
import time

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

for i in devices:
    print i

#for i in range(midi.get_count()):
#    print i
#    try:
#        p = midi.Output(i)
#        p.set_instrument(0)
#        p.note_on(69,127)
#        time.sleep(1)
#    except:
#        print "faulty channel. Must be an input not an output"
#

p = midi.Output(6)
p.set_instrument(0)
p.note_on(69, 127)
time.sleep(1)

del p

midi.quit()
Ejemplo n.º 29
0
 def __del__(self):
     if self.initialized:
         del self.midi_in
         pgm.quit()
         pg.quit()
Ejemplo n.º 30
0
def print_device_info():
    init()
    _print_device_info()
    quit()
Ejemplo n.º 31
0
 def __exit__(self, type, value, traceback):
     print "deleting DeviceSource"
     print "  uninitializing MIDI interface"
     midi.quit()
     print "  releasing video input"
     self.video_input.release()
Ejemplo n.º 32
0
def midi_close():
    midi.quit()
Ejemplo n.º 33
0
    player.note_on(cf, 127)
    time.sleep(1.23)
    player.note_off(note, 127)
    player.note_off(cf, 127)


def play_sequence(seq, cf):
    for s, c in zip(seq, cf):
        if len(s) > 2:
            snote = note_to_num[s[0:2]] + (int(s[2:3]) + 1) * 12
        else:
            snote = note_to_num[s[0:1]] + (int(s[1:2]) + 1) * 12

        if len(c) > 2:
            cnote = note_to_num[c[0:2]] + (int(c[2:3]) + 1) * 12
        else:
            cnote = note_to_num[c[0:1]] + (int(c[1:2]) + 1) * 12

        play_notes(snote, cnote)


# test_sequence = ['D3', 'D3', 'E3', 'F3', 'E3', 'D3', 'C3', 'B2', 'A2', 'C#3', 'D3']
# test_cf = ['D4', 'F4', 'E4', 'D4', 'G4', 'F4', 'A4', 'G4', 'F4', 'E4', 'D4']
#
# ali_a = ['F4', 'F4', 'C#4', 'C4', 'C4', 'G#3', 'C4', 'C4', 'G#3', 'F3', 'F3']
#
# play_sequence(test_sequence, test_cf)

del player
pm.quit()
Ejemplo n.º 34
0
def allstop():
    midi.quit()
    mixer.quit()
Ejemplo n.º 35
0
 def exit():
     midi.quit()
Ejemplo n.º 36
0
 def __del__(self):
     """Destroy MIDI communication channel"""
     logging.debug('Quitting Pygame MIDI')
     midi.quit()
Ejemplo n.º 37
0
 def __del__(self):
     midi.quit()
     print("exiting MIDI")
Ejemplo n.º 38
0
def close():
    if out:
        out.close()
    if m_in:
        m_in.close()
    pm.quit()
Ejemplo n.º 39
0
 def shutdown(self):
     self.live = False
     self.join()
     midi.quit()
Ejemplo n.º 40
0
def clean_up():
    print('Cleaning up')
    midi_input.close()
    midi.quit()
Ejemplo n.º 41
0
# Display program background
window.blit(background, (0, 0))
window.blit(blacks, (9, 261))
window.blit(blacks, (9, 381))
window.blit(blacks, (9, 501))
update_dev(0)
pg.display.flip()

#******************************************************************** MAIN LOOP
while running:
  events = pg.event.get()
  for e in events:
    if e.type in [pg.QUIT]:
      del idev
      midi.quit()
      sys.exit()
    if e.type in [pg.KEYDOWN]:
      recording = True
  k1 = 0 # keyboard 1 current max value
  k2 = 0 # keyboard 2 current max value
  k3 = 0 # keyboard 3 current max value
  note = [0] * 128 # [note id]
  for i in range(128):
    # Volume, timestamp, hit count, duration, duration * volume
    note[i] = {'vol': 0, 'stamp': 0, 'hits': 0, 'dur': 0, 'dvol': 0}
  if recording:
    pg.event.clear()
  while recording:
    events = pg.event.get()
    for e in events:
Ejemplo n.º 42
0
    def run(self):
        self.device_changed.wait()
        while self.live:
            self.device_changed.clear()

            # open the pending midi device
            self.device_lock.acquire()
            assert (self.current_device is None)
            assert (self.pending_device is not None)
            if midi.get_device_info(self.pending_device)[-1] == 1:
                # HACK: portmidi thinks the device is still open, so, uh
                # lets hope the user didn't unplug anything or plug anything new in D:
                midi.quit()
                midi.init()
            self.current_device = midi.Input(self.pending_device)
            self.pending_device = None
            self.device_lock.release()

            # listen for midi events until a new midi device is set
            while self.live and not self.device_changed.is_set():
                if self.live and self.current_device.poll():
                    packet, timestamp = self.current_device.read(1)[0]
                    status, data1, data2, data3 = packet

                    message = status >> 4
                    channel = status & 0xF
                    if not self.paused and (message is NOTE_ON
                                            or message is NOTE_OFF):
                        note = data1 + self.transpose + self.octave
                        while note < ROOT_NOTE:
                            note += self.period
                        while note > ROOT_NOTE + 36:
                            note -= self.period
                        note = max(note, ROOT_NOTE)
                        note = min(note, ROOT_NOTE + 36)
                        symbol = SYMBOLS[note - ROOT_NOTE]
                        if message is NOTE_ON:
                            win32api.keybd_event(symbol, 0, 0, 0)
                            time.sleep(0.03)
                        else:
                            win32api.keybd_event(symbol, 0, 2, 0)

                    elif message is CONTROL_CHANGE:
                        control = data1
                        value = data2 / 127.0
                        if control == 1:
                            scale = 7 if channel == 0 else 3
                            self.rest_selection = scale - round(value * scale)
                            self.ctrl_press(self.rest_selection + F1_KEY)

                    elif message is PITCH_BEND:
                        bend = (((data2 << 7) | data1) / (2**14)) - 0.5
                        symbol = None
                        if channel == 0:
                            symbol = self.full_party_select(bend)
                        elif channel == 1:
                            symbol = self.light_party_select(bend)
                        elif channel == 2 and bend != 0.0:
                            symbol = F9_KEY if bend < 0 else F10_KEY
                        self.ctrl_press(symbol)

                    elif self.use_rock_octave and message is SYSETM:
                        self.octave = 0 if (channel & 4) == 4 else 12

                time.sleep(0.001)
                if self.release is not None:
                    #print(f"Released F{self.debug_fkey(self.release)}")
                    win32api.keybd_event(self.release, 0, 2, 0)
                    self.release = None

            # close the current midi device
            self.current_device.close()
            self.current_device = None
Ejemplo n.º 43
0
 def __del__(self):
     midi.quit()
Ejemplo n.º 44
0
 def close(self):
     self._midiIn.close()
     self._midiOut.close()
     midi.quit()
Ejemplo n.º 45
0
		def __del__( self ):
			midi.quit()
Ejemplo n.º 46
0
def end():
  midi.quit()