def get_input_and_output_devices(verbose=False): INTERFACE_NAME = b"UM-2" # Edirol UM-2 EX # INTERFACE_OTHER_NAME = b"MIDIOUT2 (UM-2)" # INTERFACE_NAME = b"US-144" # Tascam US-144 infos = [ midi.get_device_info(device_id) for device_id in range(midi.get_count()) ] if verbose: print("got midi infos:", infos) input_device_id = None output_device_id = None alt_device_id = None for device_id, info in enumerate(infos): interf, name, is_input, is_output, is_opened = info if name == INTERFACE_NAME: if is_input: input_device_id = device_id elif is_output: output_device_id = device_id elif name == INTERFACE_OTHER_NAME: raise Exception( "OTHER_NAME should not be used; check that input/output device names are as you expect" ) alt_device_id = device_id if input_device_id is None or output_device_id is None: print( "MIDI input and/or output could not be correctly identified. Result: input {}; output {}" .format(input_device_id, output_device_id)) inp = midi.Input(input_device_id) if input_device_id is not None else None outp = midi.Output( output_device_id, latency=1 ) if output_device_id is not None else None # if latency is 0 then timestamps are ignored by pygame return inp, outp
def play(self): if self.state is PlayerState.PLAYING: return if not self.output: self.output = midi.Output(self.get_midi_output_id()) self.output.set_instrument(self.INST_NYLON_GUITAR, 1) noteEvents = [] sheet = self.sheet for timeStart, timeEnd, note in sheet.iter_note_sequence(): # note on noteEvents.append(NoteEvent(timeStart, EventType.NOTE_ON, note)) # note off noteEvents.append(NoteEvent(timeEnd, EventType.NOTE_OFF, note)) noteEvents.sort(key=lambda x: x[:2]) self.thread = thread = Thread(target=self._run, args=(noteEvents,)) thread.daemon = True self.state = PlayerState.PLAYING thread.start() else: self._sync_time(self.get_current_time()) self.state = PlayerState.PLAYING
def run(self): midi.init() try: output = midi.Output(2) except Exception as e: print("Problem with keyboard output") print(e) exit() ser = serial.Serial(gloveUSB, 9600) time.sleep(3) print(self.song) while True: if self.stopped(): return ser.write(self.songName.encode()) # serLed = serial.Serial(ledUSB, 9600) # time.sleep(2) # serLed.write(self.songName.encode()) time.sleep(1) i = 0 song = self.song while i < len(song): if i > 0: time.sleep(song[i][2] / 1000) output.note_on(song[i][0], 80, 0) if i + 1 != len(song) and song[i + 1][2] == 0: output.note_on(song[i + 1][0], 80, 0) time.sleep(song[i][1] / 1000) output.note_off(song[i][0], 0, 0) output.note_off(song[i + 1][0], 0, 0) i = i + 2 else: time.sleep(song[i][1] / 1000) output.note_off(song[i][0], 0, 0) i = i + 1 time.sleep(20)
def _open(self, **kwargs): 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 lp_connect(self, devsig): devsigin = ('ALSA', devsig, 1, 0, 0) devsigout = ('ALSA', devsig, 0, 1, 0) pm.init() for i in xrange(pm.get_count()): _ = pm.get_device_info(i) if _ == devsigin: lpin = pm.Input(i) print " -> Found In" if _ == devsigout: lpout = pm.Output(i) print " -> Found Out" if lpin == None or lpout == None: print "Didn't find controller" sys.exit(1) # initialize controller (reset, select X-Y mode) lpout.write_short(0xB0, 0x00, 0x00) lpout.write_short(0xB0, 0x00, 0x01) return [lpin, lpout]
def setOutputDevice(self, output_port): self.output_port = output_port self.outDev = pm.Output(output_port)
cmd += ["-e", fieldName] if targs: cmd += targs if verbose: print("Starting TShark with '{}'".format(" ".join(cmd))) try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) except FileNotFoundError: sys.exit("Unable to locate TShark executable at {}".format(tshark)) # Set up midi midi.init() port = midi.get_default_output_id() if verbose: print("Outputting to {}".format(midi.get_device_info(port))) midiOut = midi.Output(port) if drum: beatTimer = repeatTimer(beat[0], drumbeat) beatTimer.start() activeNotes = [] # threads currently playing queuedNotes = [] # notes to play for line in p.stdout: if stopping: continue # TShark output is tab delimited capture = line.strip("\n").split("\t") if verbose >= 2: print(">> {}".format(capture))
# These imports are necessary for PyLance to autocomplete for some reason #isort:split import pygame.display import pygame.draw import pygame.event import pygame.key import pygame.time #isort:split from pygame import * from pygame.locals import * pygame.init() from typing import Optional from pygame import midi MIDI_DEVICE: Optional[midi.Output] MIDI_ENABLED: bool try: midi.init() MIDI_DEVICE = midi.Output(midi.get_default_output_id()) MIDI_ENABLED = True except (pygame.error, midi.MidiException) as e: import sys print('Unable to load midi:', e, file=sys.stderr) MIDI_DEVICE = None MIDI_ENABLED = False
for i in range(midi.get_count()): print midi.get_device_info(i) # Prompt user for input device ipDev = input("Choose input device:") x = midi.Input(ipDev, 0) x.read(1) # Prompt user for output device opDev = input("Choose output device:") player = midi.Output(2, latency=0) player.set_instrument(2) # Continous loop which checks for MIDI events from the input device and plays # them on the output device. while True: if x.poll(): # if there is a MIDI event midiEvents = x.read(1)[0] # read the event note = midiEvents[0][1] vel = midiEvents[0][2] if vel != 0: player.note_on(note, vel) else: player.note_off(note, vel)
''' bee_note_sound special sound format for bee BeeNoteSoundFrame: Tuple[time, type, padding, data] ''' import ustruct as struct from machine import Pin, PWM from micropython import const from utime import ticks_ms, ticks_diff, ticks_add from play32hw.shared_timer import ONE_SHOT, get_shared_timer from os import environ environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' from pygame import midi as pyg_midi pyg_midi.init() _pyg_output = pyg_midi.Output(0) TYPE_EMIT_EVENT = const(0X00) TYPE_SET_TEMPO = const(0X01) TYPE_NOTE_ON = const(0X02) TYPE_NOTE_OFF = const(0X03) _DEFAULT_TICKS_PER_BEAT = const(480) _DEFAULT_TEMPO = const(500_000) _FREQ_QUITE = const(100_000) # index 0 is note C0 _NOTE_FREQ = [ 16, 17, 18, 19, 21, 22, 23, 24, 26, 28, 29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 58, 62, 65, 69, 73, 78, 82, 87, 92, 98, 104, 110, 117, 123, 131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1046, 1109, 1175, 1244, 1318, 1397, 1480, 1568, 1661, 1760, 1865, 1976,
def Setup(): PrintWithTime("Program started") #First we read the config to correctly define our global variables global SETUP_JSON #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 try: SETUP_JSON = json.loads(''.join( open("Config\\" + Filename + ".json", "r"))) except FileNotFoundError: PrintError("Config " + Filename + " not found") PrintError("Exiting program") exit() except: PrintError("Couldn't open " + Filename + ".json") PrintError("Exiting program") exit() else: PrintWithTime("Opened config: " + Filename) #Define the global 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: PrintError("ERROR 404: ConfigName argument was not found") if "StudioModeDefault" in config_general: global StudioModeDefault StudioModeDefault = config_general["StudioModeDefault"] else: PrintError("ERROR 404: StudioModeDefault argument was not found") if "DefaultTransition" in config_general: global DefaultTransition DefaultTransition = config_general["DefaultTransition"] else: PrintError("ERROR 404: DefaultTransition argument was not found") if "DefaultTransitionDuration" in config_general: global DefaultTransitionDuration DefaultTransitionDuration = config_general[ "DefaultTransitionDuration"] else: PrintError( "ERROR 404: DefaultTransitionDuration argument was not found") if "server_ip" in config_general: global server_ip server_ip = config_general["server_ip"] else: PrintError("ERROR 404: server_ip argument was not found") if "server_port" in config_general: global server_port server_port = config_general["server_port"] else: PrintError("ERROR 404: server_port argument as not found") if "server_password" in config_general: global server_password server_password = config_general["server_password"] else: PrintError("ERROR 404 server_password argument was not found") if "SceneCollection" in config_general: global SceneCollection SceneCollection = config_general["SceneCollection"] else: PrintError("ERROR 404 SceneCollection argument was not found") del config_general else: PrintError("No general config in config file") global config_pad if "config_pad" in SETUP_JSON: config_pad = SETUP_JSON["config_pad"] del SETUP_JSON else: PrintError("No pad config in config file") PrintError("Exiting program") exit() #Here we connect to the OBS Websocket global ws try: ws = obsws(server_ip, server_port, server_password) ws.connect() except: PrintError("Connection to OBS Websocket is impossible") PrintError("Exiting program") exit() else: PrintWithTime("Connected to Websocket") #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) except: PrintError("Midi Pad not found") PrintError("Exiting program") exit() else: PrintWithTime("Connected Midi Pad") #Here we set up OBS like configured global OldSceneCollection try: OldSceneCollection = ws.call(requests.GetCurrentSceneCollection()) OldSceneCollection = OldSceneCollection.getScName() except: PrintError("Couldn't get scenecollection") SetSceneCollection({"SceneCollection": SceneCollection}) #if str(CheckStudioState()) != StudioModeDefault: # ToggleStudioMode({}) SetTransition({ "Transition": DefaultTransition, "TransitionDuration": DefaultTransitionDuration }) PrintWithTime("Program is ready to use")
def test(): pgmidi.Output(device).note_on(60, 100, 0) time.sleep(0.5) pgmidi.Output(device).note_off(60, 100, 0)
def __init__(self, readChennel, outputChannel): midi.init() self.read = midi.Input(readChennel) self.output = midi.Output(outputChannel)
def __init__(self, port): pygame.init() midi.init() self.midiOut = midi.Output(port)
from multiprocessing import Value import json midi.init() device = "Midi Fighter Twister MIDI 1" conf_file = "./config.json" mail = 0 bank = 4 for i in range(midi.get_count()): devInfo = midi.get_device_info(i) if(re.compile(device).search(devInfo[1]) and devInfo[3] == 1): print devInfo[1] outp = midi.Output(i) inp = midi.Input(i + 1) k2000.initialize_mf(outp, bank) break if len(sys.argv) > 1: fp = open(sys.argv[1]) else: fp = open(conf_file, 'r') js = json.load(fp) config = {} for j in js.keys(): config[j] = ['blink', (outp, bank, js[j]['line'], js[j]['column'], js[j]['color'], js[j]['mode']), 0 ]
def __init__(self, devs): MidiIo.__init__(self, midi.Output(devs.forOutput(), latency = 0))
def OpenOutput(self, midi_id): if self.devOut is None: self.devOut = midi.Output(midi_id, 0, MIDI_BUFFER_OUT)
def getMidiOutputDevice(id): return midi.Output(id)
""" sequence.append((8 * qNote, 0)) # dummy event indicates end of bar """ Go Animal Go for i in range(12): sequence.append((qNote*8 + i*qNote/3,tom[random.randint(0,len(tom)-1)])) sequence.append((8*qNote+12*qNote/3,0)) # dummy event indicates end of bar """ while True: seq = list(sequence) # create copy of sequence seq.sort(reverse=True) event = seq.pop() timeZero = time.time() * 1000 print("Loop start") while True: now = time.time() * 1000 if now - timeZero > event[0]: print(event[1]) if event[1] > 0: pgmidi.Output(device).note_on(event[1], velocity, drumChannel) if seq: # if events left in queue event = seq.pop() else: break # if no events left, break from this loop else: time.sleep(0.01) # if time for event hasn't come, wait
import random import sys import time import pygame from pygame import midi FRAMEWIDTH = 500 RECTWIDTH = 10 INSTRUMENT_ID = 54 # 54 pygame.init() midi.init() PLAYER = midi.Output(0) PLAYER.set_instrument(INSTRUMENT_ID, 1) CANVAS_SIZE = round(FRAMEWIDTH / RECTWIDTH) FRAMEHEIGHT = FRAMEWIDTH + 100 def draw_rect(x1, y1, x2, y2, win, color=(90, 0, 140)): pygame.draw.rect(win, color, (x1, y1, x2, y2), 0) for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.flip() def pling(note): if RECTWIDTH == 1: return
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' from pygame import midi import pickle import rlcompleter import readline readline.parse_and_bind("tab: complete") #it would be nice if these were constants midi.init() midi_out = midi.Output(midi.get_default_output_id()) hi = [0xf0, 0x7e, 0x7f, 0x07, 0x06, 0x01, 0xf7] default = [ 0xf0, 0x00, 0x01, #3 0x5f, 0x7a, 0x1a, 0x00, 0x01, 0x00, 0x02, 0x22, 0x20, 0x2e,
def __init__(self, output=0, instrument=0): if not MidiPlayer.inited: self.init() self.__player = midi.Output(output) self.__player.set_instrument(instrument)
def __init__(self, out_port: int, in_port: int): self.connection = midi.Output( out_port) #set port to set button response self.input = midi.Input(in_port) #set port to recieve RGB signals
import pygame.midi as pm import time pm.init() player = pm.Output(0) player.set_instrument(0, 1) note_to_num = { 'C': 0, 'C#': 1, 'D': 2, 'D#': 3, 'E': 4, 'F': 5, 'F#': 6, 'G': 7, 'G#': 8, 'A': 9, 'A#': 10, 'B': 11, } def play_notes(note, cf): player.note_on(note, 127) player.note_on(cf, 127) time.sleep(1.23) player.note_off(note, 127) player.note_off(cf, 127)
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()
elif (isoutput): direction = "OUTPUT" print(f" [{direction}{', opened' if opened else ''}]") print(f" Device: {i}") print(f" Interface: {interface.decode()}") print(f" Name: {name.decode()}") # Check if device we're looking for if (name.decode().find(namePattern)): if (isoutput): outputDeviceIndex = i elif (isinput): inputDeviceIndex = i # Open launchpad device(s) outputDevice = midi.Output(outputDeviceIndex) # Play with colors # Clear LED:s for i in range(9): for j in range(9): # Turn off all lights outputDevice.write_short(0x80, (i * 10) + j) # Cycle all colours on center pads for i in range(128): outputDevice.write_short(0x90, 54, i) outputDevice.write_short(0x90, 55, i) outputDevice.write_short(0x90, 44, i) outputDevice.write_short(0x90, 45, i)
print(usage) sys.exit() if part == 0: songName, song = getSongs(id, condition) else: songName, song = getSongPart(id, condition, part) print(songName) print(song) KEYDOWN = 144 KEYUP = 128 midi.init() try: output = midi.Output(2) except Exception as e: print("Problem with keyboard output") print(e) exit() #serGlove = serial.Serial(gloveUSB, 9600) #time.sleep(2) #serGlove.write(songName.encode()) #time.sleep(1) i = 0 while i < len(song): if i > 0: time.sleep(song[i][2]/1000) output.note_on(song[i][0], 80, 0) if i+1 != len(song) and song[i+1][2] == 0:
import pygame.midi import threading import time import atexit midi = pygame.midi midi.init() mixer = pygame.mixer mixer.init() i = midi.Input(1) o = midi.Output(2) def passthrough(): while True: b = i.read(50) o.write(b) time.sleep(0.01) def allstop(): midi.quit() mixer.quit() atexit.register(allstop)
from pygame import midi as m import time m.init() print(m.get_count()) midi = m.Output(1) midi.set_instrument(64, 0) midi.set_instrument(64, 1) midi.note_on(48, 100) for i in range(48, 56): midi.note_on(i, 100, 1) time.sleep(0.8) midi.note_off(i, 100, 1) midi.note_off(48, 100, 0) time.sleep(10) for i in range(0, 127): midi.set_instrument(i, 0) for j in range(48, 72): midi.note_on(j, 127) time.sleep(0.04) midi.note_off(j, 127) print(i)
def init_hardware(self, interface_name): input_id, output_id = get_devices(interface_name) if input_id is None or output_id is None: raise IOError self.input = midi.Input(input_id) self.output = midi.Output(output_id)