def main(): cliente_destino = int(sys.argv[1]) archivo = sys.argv[2] trios = [] for e in sys.argv[3:]: n, tempo, compases = list(map(int, e.split())) trios.append((n, tempo, compases)) import alsaseq alsaseq.client('Reproductor', 0, 1, True) alsaseq.connectto(0, cliente_destino, 0) alsamidi.queue = 1 def play(eventos): 'Envia lista de eventos a la cola del secuenciador.' alsaseq.start() for evento in eventos: alsaseq.output(evento) alsaseq.syncoutput() ritmos = lee(archivo) print(len(ritmos), 'ritmos:', [x[0] for x in ritmos]) eventos = [] end = 0 for trio in trios: n, tempo, compases = trio ritmo = ritmos[n] eventos.extend(construye(ritmo, tempo, compases, end)) print(str(end).rjust(5), str(compases).rjust(3), ritmo[0]) end = end + compases * int(60. / tempo * 1000) * ritmo[1][0] play(eventos)
def init_alsa(self): # prepare alsaseq device_no = self.options[ "midi_device_no"] # find out using aconnect or aconnectgui alsaseq.client('Recorder', 1, 0, True) alsaseq.connectfrom(0, device_no, 0) alsaseq.start()
def __init__(self, addr=None, channel=1): self.ctrl_param = 98 self.channel = channel - 1 alsaseq.client('Aeolus-OSC', 0, 1, True) alsaseq.start() self.src = (alsaseq.id(), 0) log.info('I am %s:%s' % (str(self.src[0]), str(self.src[1]))) self.update_connection(addr) # from help(alsaseq): # # ALSA events are returned as a tuple with 8 elements: # (type, flags, tag, queue, time stamp, source, destination, data) # # Some elements are also tuples: # time = (seconds, nanoseconds) # source, destination = (client, port) # data = ( varies depending on type ) # # See DATA section below for event type constants. # # This API is nuts. # TODO should send events to subscribed ports not directly to aeolus self.presets = None
def main(): se = ServoEvent() parser = MusicParser() alsaseq.client('RoboWhistle PassThrough', 1, 1, False) # Set up a new ALSA channel alsaseq.connectfrom( 1, 129, 0) # Midi file input needs to be sent in to channel 129 # Backup ALSA channel to run on port 128. Can use either a virtual synth (e.g. Timidity or a physical MIDI keyboard) alsaseq.connectto(1, 128, 0) srv = ServoEvent() srv.ResetServoEvent() #To enter FreePlay mode provide any argument when running the program; if left blank AutoPlay will proceed automaticlly if len(sys.argv) is 2: print "Entering FreePlay Mode" play = FreePlay() play.ManualPlay() else: print str(len(sys.argv)) while 1: if alsaseq.inputpending(): # ALSA queue event = alsaseq.input() # Pop event from top of the queue eventPitch = event[7][ 1] # Pitch of the note that needs to be played parsedNote = parser.AnalyseSingleNote(eventPitch % 12) if parsedNote is None: alsaseq.output( event ) # Event is unplayable by the whistle, forward it to the synthesiser else: se.PlayNoteEvent(parsedNote) # Pass item for playing
def __init__(self, preferred_port=None): super().__init__() self.keep_running = True self.client_id = 0 self.client_port = 0 self.time_s = 0 self.time_ns = 0 self.add_s = 0 self.add_ns = 0 self.enqueue_at_once = 24 # this call causes /proc/asound/seq/clients to be created alsaseq.client('MidiClock', 0, 1, True) client_name = "" for client in iter_alsa_seq_clients(): self.client_id = client[0] client_name = client[1] self.client_port = client[2][0] logging.info("found port {} at {}:{}".format( client_name, self.client_id, self.client_port)) if client_name == preferred_port: break logging.info("Using port {} at {}:{}".format(client_name, self.client_id, self.client_port)) alsaseq.connectto(0, self.client_id, self.client_port)
def main(): cliente_destino = int( sys.argv[1] ) archivo = sys.argv[2] trios = [] for e in sys.argv[3:]: n, tempo, compases = list(map( int, e.split() )) trios.append( ( n, tempo, compases ) ) import alsaseq alsaseq.client( 'Reproductor', 0, 1, True ) alsaseq.connectto( 0, cliente_destino, 0 ) alsamidi.queue = 1 def play( eventos ): 'Envia lista de eventos a la cola del secuenciador.' alsaseq.start() for evento in eventos: alsaseq.output( evento ) alsaseq.syncoutput() ritmos = lee( archivo ) print(len(ritmos), 'ritmos:', [x[0] for x in ritmos]) eventos = [] end = 0 for trio in trios: n, tempo, compases = trio ritmo = ritmos [ n ] eventos.extend( construye( ritmo, tempo, compases, end ) ) print(str( end ).rjust( 5 ), str( compases ).rjust( 3 ), ritmo[ 0 ]) end = end + compases * int( 60. / tempo * 1000 ) * ritmo[1][0] play( eventos )
def __init__(self): print('Using ALSA MIDI interface') alsaseq.client('Simple', 1, 1, False) # name, ninputports, noutputports, createqueue alsaseq.connectfrom(0, CLIENT, 0) # inputport, src_client, src_port self.binds = {}
def music(): global esn, visualiser train_skip = sys.argv[1] test_skip = sys.argv[2] input, output, esn = test_data.bach() n_forget_points = 0 alsaseq.client('andreas', 1, 1, True) alsaseq.connectto(1, 20, 0) alsaseq.start() visualiser = Visualiser(esn) if len(sys.argv) < 4: state_matrix = esn.train(input, output, n_forget_points=n_forget_points, callback_every=int(train_skip), callback=refresh_midi) else: with open(sys.argv[3]) as f: esn.unserialize(cPickle.load(f)) visualiser.set_weights() esn.reset_state() esn.noise_level = 0 print 'test' estimated_output = esn.test(input, callback=refresh_midi, n_forget_points=n_forget_points, callback_every=int(test_skip)) error = nrmse(estimated_output, output) print 'error: %s' % error
def MIDIgen(self): # Try to run using a platform-specific backend if platform.system() == "Linux" and alsa_ok: alsaseq.client("Audionodes", 1, 1, False) while True: if alsaseq.inputpending(): inputData = alsaseq.input() if inputData[0] in (6, 7): # Key f = 440 * (2**((inputData[-1][1] - 48) / 12)) yield { "type": "key", "frequency": f, "velocity": inputData[-1][2], "note": inputData[-1][1] } elif inputData[0] in (10, ): # Sustain yield { "type": "sustain", "velocity": inputData[-1][-1] } time.sleep(0.01) # If such is not available, fall back to PyGame else: pygame.init() midi.init() inputdata = midi.Input(midi.get_default_input_id()) def toDict(event): velocity = event[0][0][2] # Sustain if event[0][0][0] == 176 and event[0][0][1] == 64: return {"velocity": velocity, "type": "sustain"} elif event[0][0][0] == 144: note = event[0][0][1] f = 440 * (2**((note - 48) / 12)) return { "type": "key", "velocity": velocity, "note": note, "frequency": f } while 1: if inputdata.poll(): event = inputdata.read(1) if toDict(event) != None: print(toDict(event)) yield toDict(event) time.sleep(0.01)
def __init__(self, lock, volumePoint, notePoint, channel): threading.Thread.__init__(self) self.stop = threading.Event() self.volumePoint = volumePoint self.notePoint = notePoint self.channel = channel self.lock = lock self.sleepDelay = 0.03 alsaseq.client("therminal", 0, 1, False) alsaseq.start()
def __init__(self, lock, pointA, pointB, channel): threading.Thread.__init__(self) self.stop = threading.Event() self.pointA = pointA self.pointB = pointB self.lock = lock self.channel = channel self.sleepDelay = 0.03 alsaseq.client("druminal", 0, 1, False) alsaseq.start()
def __init__(self): super().__init__() self.keep_running = True self.client_id = None self.client_port = None self.time_s = 0 self.time_ns = 0 self.add_s = 0 self.add_ns = 0 self.enqueue_at_once = 24 # this call causes /proc/asound/seq/clients to be created alsaseq.client('MidiClock', 0, 1, True)
def __init__(self, invoker, env, settings): BaseExhibit.__init__(self, invoker, env, settings) self.env.game_load.listen_once(self.reset_game) self.env.game_load.listen_once(self.qr_register) os.system("pkill timidity") os.system("timidity -iA -Os &") alsaseq.client( 'Simple', 1, 1, True ) alsaseq.connectto( 1, 128, 0 ) alsaseq.start() self.st.max_tone_amount = 3 self.tones_amount = 0
def play(predicted): import alsaseq, alsamidi alsaseq.client('andreas', 1, 1, True) alsaseq.connectto(1, 20, 0) alsaseq.start() for pitches in predicted.T: for i, on in enumerate(pitches): note = i + 50 alsaseq.output(alsamidi.noteoffevent(0, note, 100)) if on: alsaseq.output(alsamidi.noteonevent(0, note, 100)) time.sleep(.1)
def run(self): import select alsaseq.client(appinfo.name, self.num_inports, self.num_outports, True) self.start_time = datetime.now() alsaseq.start() log.debug("ALSA sequencer started") alsafd = alsaseq.fd() while not self.join_req: fds_ready = select.select([alsafd], [], [], 0.1) if alsaseq.inputpending(): raw_event = alsaseq.input() new_event = self.create_event(raw_event) self.dispatch_event(new_event)
def run(clientName, inPorts, outPorts, controller): curScreen = controller alsaseq.client(clientName, inPorts, outPorts, True) initd = False while True: if not alsaseq.inputpending(): time.sleep(0.001) continue val = alsaseq.input() mtype = val[0] if mtype == _MIDI_CONNECT: __devi = val[7][0] __devo = val[7][2] initd = True elif not initd: continue elif mtype == _MIDI_CC: but = val[7][4] vel = val[7][5] r,c = __b2idx(but) if c == 9: but = PLAY if vel == 0: curScreen.onButtonUp(but, 9 - r, c) else: curScreen.onButtonDown(but, vel, 9 - r, c) elif mtype == _MIDI_ON: but = val[7][1] vel = val[7][2] r,c = __b2idx(but) if vel == 0: curScreen.onButtonUp(but, 9 - r, c) else: curScreen.onButtonDown(GRID, vel, 9 - r, c) elif mtype == _MIDI_OFF: but = val[7][1] vel = val[7][2] r,c = __b2idx(but) curScreen.onButtonUp(GRID, 9 - r, c) elif mtype == _MIDI_MAFTER: vel = val[7][5] curScreen.onMonoAftertouch(vel) elif mtype == _MIDI_PAFTER: but = val[7][1] vel = val[7][2] r,c = __b2idx(but) curScreen.onPolyAftertouch(9 - r, c, vel)
def run(self): import select alsaseq.client(appinfo.name, self.num_inports, self.num_outports, True) self.start_time = datetime.now() alsaseq.start() log.debug("ALSA sequencer started") alsafd = alsaseq.fd() while not self.join_req: fds_ready = select.select([alsafd], [], [], 0.1) if alsaseq.inputpending(): raw_event = alsaseq.input() new_event = self.create_event(raw_event) self.dispatch_event(new_event) alsaseq.stop() alsaseq.close()
def Open(self, src_list=[], dest_list=[]): ''' src_list is a list of src ports to connect to. From -i#,# dest_list is a list of dest ports to connect to. From -o#,#, ''' print('opening alsaseq client') junk_None = alsaseq.client( 'midiroute', # name of virtual client 1, #num in ports 1, #num out ports False) # create_queue Y/N - rx buf? # there is also connectto(), connectfrom() funcs... # these appear to be for connecting client() to other ports # following input port, output port appear to be 0 for input, # 1 for output. for src_i in src_list: print('in:%d' % (src_i)) alsaseq.connectfrom(0, # input port src_i, # src client 0) # src port for dest_i in dest_list: print('out:%d' % (dest_i)) alsaseq.connectto(1, # output port(first one of ours?) dest_i, # dest client 0) # dest port # connect ins and outs based on string comparisons: # see ourAlsaIn()/Out() above for setting your string connect matches #if len(src_list) == 0 and len(dest_list) == 0: if self.auto_midi_conn: # -a[0|1] option, default 1 on print('scanning Alsa Midi Inputs') lst = AlsaSeq_List(0) # list inputs(Midi Keys for ex) for m in lst: if ourAlsaIn(m): print('connect input client %3d %-26s port %d %s' % (m.client_id,m.client_name, m.port_id,m.port_name)) alsaseq.connectfrom(m.port_id, # our port, first input is 0 m.client_id, # 28 for example m.port_id) # 0 for example print('scanning Alsa Midi Outputs') lst = AlsaSeq_List(1) # list outputs(synth ex) for m in lst: if ourAlsaOut(m): print('connect output client %3d %-26s port %d %s' % (m.client_id,m.client_name, m.port_id,m.port_name)) alsaseq.connectto(1, # our first output port is 1 now m.client_id, # 28 for example m.port_id) # 0 for example # how do we tell if successful? This is returning None? # it calls exit(1) if fails, I guess client is not expected # to fail... self.mDevIn = True if self.mDevIn != None: return True # ok print('fail!') return False # no open
def __init__(self, invoker, env, settings): BaseExhibit.__init__(self, invoker, env, settings) self.env.game_load.listen_once(self.reset_game) self.env.game_load.listen_once(self.qr_register) try: logger.info(os.system("pgrep timidity")) logger.info(os.system("pkill timidity")) logger.info(os.system("timidity -iA -Os -B5,12 &")) #logger.info(os.system("timidity -iA -Os")) time.sleep(2) #essential for good connection alsaseq.client( 'Simple', 1, 1, True ) alsaseq.connectto( 1, 128, 0 ) alsaseq.start() logger.info("timidity is ok. (i hope)") except Exception as e: logger.error("timidity" + str(e)) self.st.max_tone_amount = 3 self.tones_playing = []
def main(dest_client, file_name, display=False): seq = alsamidi.Seq() seq.read(file_name) events = alsamidi.merge(seq.tracks) seq.info() print(len(events), 'events') alsaseq.client('aseqplay', 0, 1, 1) alsaseq.connectto(0, dest_client, 0) for channel in range(16): alsaseq.output(alsamidi.pgmchangeevent(channel, 0)) alsaseq.start() for event in events: if display: print(event) alsaseq.output(event) alsaseq.syncoutput()
def pickOutput(self): if self.mDevOut: print('closing existing output') del self.mDevOut self.mDevOut = None dev = -1 if back_end == 'pypm': os.system('aconnect -o') # list out devices according to alsa: self.PrintDevices(OUTPUT) # print selection list according to pyportmidi dev = GetNumPrompt('Enter output device number:', -1) if dev == -1: print('no output picked') return False if back_end == 'pypm': latency = 20 # msec latency. self.mDevOut = pypm.Output(dev, latency) elif back_end == 'alsaseq': print('alsaseq opening input/output virtual client') if not self.mDevIn: junk = alsaseq.client('py_alsaseq', 1, 1, False) # returning None self.mDevIn = 1 self.mDevOut = self.mDevIn elif back_end == 'rtmidi': print('rtmidi opening input/output virtual client') self.mDevIn = rtmidi.MidiIn() self.mDevOut = rtmidi.MidiOut() self.mDevIn.open_virtual_port("py_rtmidi") self.mDevOut.open_virtual_port("py_rtmidi") print('output open, rtmidi') elif back_end == 'mididings': print('mididings not implemented') return False print ('Midi output opened') return True
def pickInput(self): if self.mDevIn: print('closing existing input') del self.mDevIn self.mDevIn = None dev = -1 if back_end == 'pypm': # list in devices according to alsa: os.system('aconnect -i') self.PrintDevices(INPUT) dev = GetNumPrompt('Input input device number:', -1) if dev == -1: print('no input picked') return False if back_end == 'pypm': self.mDevIn = pypm.Input(dev) elif back_end == 'alsaseq': print('alsaseq opening input/output virtual client') if not self.mDevIn: junk = alsaseq.client('py_alsaseq', 1, 1, False) # returning None self.mDevIn = 1 self.mDevOut = self.mDevIn elif back_end == 'rtmidi': print('rtmidi opening input/output virtual client') self.mDevIn = rtmidi.MidiIn() self.mDevOut = rtmidi.MidiOut() self.mDevIn.open_virtual_port("py_rtmidi") self.mDevOut.open_virtual_port("py_rtmidi") print('open input rtmidi') elif back_end == 'mididings': print('mididings not implemented') return False print('Midi input opened.') return True
if (status[0]*1000 + status[1]/1000000) > self.target: self.position = self.target + self.period self.output_pulses() def output_pulses(self): for i in range(self.position, self.position + self.period, self.pulse_period): alsaseq.output((alsaseq.SND_SEQ_EVENT_CLOCK, 1, 0, 1, (i // 1000, (i%1000) * 1000000), (0, 0), (0, 0), (0, 0, 0, 0, 0))) self.target = self.position alsaseq.client('Midi Clock', 0, 1, True) alsaseq.start() midiclock = MidiClock(period) while True: status = alsaseq.status() midiclock.check_target(status[1])
import alsaseq import time from alsamidi import noteonevent, noteoffevent #alsaseq.client( 'MIDI through', 1, 1, False ) #alsaseq.connectfrom( 1, 129, 0 ) #alsaseq.connectto( 0, 130, 0 ) alsaseq.client( 'Simple', 1, 1, True ) alsaseq.connectto( 1, 128, 0 ) alsaseq.start() _akord=[0,4,7] akord=[i+12*j for i in _akord for j in range(1)] for base in range(40): events=[(1, 40+base+i, 120) for i in akord] noteons=[noteonevent(*event) for event in events] noteoffs=[noteoffevent(*event) for event in events] s=raw_input("stlac enter") for noteon in noteons: alsaseq.output(noteon) time.sleep(1) for noteoff in noteoffs: alsaseq.output(noteoff) time.sleep(0.2) time.sleep(10)
# amidisplitter.py - Tom Clayton # Connect input and out put to alsa midi streams and this program will # increment the midi channnel of notes received by one for every note # above note x. x is set with a command line argument. x defaults to # B3 (59). import alsaseq import sys if len(sys.argv) > 1: split_key = int(sys.argv[1]) else: split_key = 59 # Default, <-B3 C4-> alsaseq.client('Keyboard Splitter', 1, 1, False) # alsaseq event: # (type, flags, tag, queue, time stamp, source, destination, data) # data = (channel, note, velocity, ??, ??) while True: if alsaseq.inputpending(): event = list(alsaseq.input()) if (event[0] == 6 or event[0] == 7) and event[7][1] > split_key: data = list(event[7]) data[0] += 1 event[7] = tuple(data) #event[7][0] += 1 alsaseq.output(event)
drums(ritmos[nritmo], tempo, compases) elif letra in "0123456789": nritmo = int(letra) print("{:2} {}".format(nritmo, ritmos[nritmo][0])) elif letra == "n": number = int(input()) if number < len(ritmos): nritmo = number print("{:2} {}".format(nritmo, ritmos[nritmo][0])) elif letra == "t": tempo = int(input()) print("tempo:", tempo) rechazados = (alsaseq.SND_SEQ_EVENT_CLOCK, alsaseq.SND_SEQ_EVENT_SENSING) alsaseq.client("ReproductorGrabador", 1, 1, 1) alsaseq.connectfrom(0, source_cliente, 0) alsaseq.connectto(1, dest_cliente, 0) alsaseq.start() pgmchangevoz1 = alsamidi.pgmchangeevent(0, voz1) pgmchangevoz2 = alsamidi.pgmchangeevent(1, voz2) alsaseq.output(pgmchangevoz1) if voz2: alsaseq.output(pgmchangevoz2) nlibres = 100 import kbhit kbhit.unbuffer_stdin() vivo = 1 seq = alsamidi.Seq()
# Connect input and alsa midi stream and set output to a serial port. # This program will send note on and note off messages recevied on # the midi stream to the serial port. Serial port is set with a command # line input. import alsaseq import serial import sys if len(sys.argv) < 2: print("Enter serial port as command line argument.") sys.exit() synth = serial.Serial(port=sys.argv[1], baudrate= 31250, timeout=1) alsaseq.client("Midi to Serial", 1, 0, False) # alsaseq event: # (type, flags, tag, queue, time stamp, source, destination, data) # data = (channel, note, velocity, start, duration) while True: if alsaseq.inputpending(): event = list(alsaseq.input()) #print(event) if event[0] == 6: #Note on print(f'0x{144+event[7][0]:x}') print(f'0x{event[7][1]:x}') print(f'0x{event[7][2]:x}') synth.write(bytes([144+event[7][0], event[7][1], event[7][2]]))
exit(2) else: usage() exit(2) return p # ============================================================================ args = sys.argv[1:] args.append("-m") # args.append('20:14:12:17:01:67') args.append('20:14:12:17:02:47') params = parseArgs(args) # initialize ALSA alsaseq.client( 'MidiCube', 1, 1, False ) if params.alsaOut is not None: (client, port) = params.alsaOut alsaseq.connectto(0, client, port) if params.alsaIn is not None: (client, port) = params.alsaIn alsaseq.connectfrom(0, client, port) # connect to bluetooth device sock = com.connect(params.btMAC) if not sock: logging.error('connection to MIDI cube failed') exit(-1) listener = Listener(sock, params.btMAC) scheduler = Scheduler(params)
def __init__(self, client_name="Zynthian_gui"): alsaseq.client(client_name, 1, 1, True) #alsaseq.connectto(0,130,0) alsaseq.start()
import alsaseq, time, dev_board as pi alsaseq.client( 'Python', 1, 0, False ) alsaseq.connectfrom( 0, 14, 0 ) alsaseq.start() playChannels = [0 for x in range(16)] pinChannels = [0,0,0,0] pinNotes = [0,0,0,0] def midi_process(ev): global pinNotes global pinChannels if (ev[0] == alsaseq.SND_SEQ_EVENT_PGMCHANGE): #clear pins state clearPinChannels() clearPinNotes() print "PGMCHANGE: channel ", ev[7][0], " ", ev[7][5] #filter out base, percussion, or synth if (ev[7][5] >= 8 and ev[7][5] <= 15) or (ev[7][5] >= 32 and ev[7][5] <= 39) or (ev[7][5] >= 88 and ev[7][5] <= 103): setPlayChannel(ev[7][0], 0) else: setPlayChannel(ev[7][0], 1) #if event is NOTEON(6) or NOTEOFF(7) elif (ev[0] == 6) or (ev[0] == 7): #print "GOT NOTE_X" if isPlayChannel(ev[7][0]):
def light(self): for name, l in self.allLights.items(): l.setController(lights.ConstantRGBController(255, 255, 255)) def setLights(self, lightList, controllerFunc): for l in lightList: self.allLights[l].setController(controllerFunc()) def setLightsExcept(self, lightExceptList, controllerFunc): for name, l in self.allLights.items(): if not name in lightExceptList: l.setController(controllerFunc()) alsaseq.client("Click", 1, 1, True) alsaseq.connectto(1, 128, 0) class ClickTrackProgram(Program): songStructure = SongStructure( [ SongSection( "All", [ SongRhythm(4, 1, 120, 120, [(i, 76) for i in range(4)] + [(i, 50 + i) for i in range(4)]), SongRhythm(4, 20, 120, 120, [(i, 76) for i in range(4)]), ], ) ] )
#! /usr/bin/env python3 import alsain import beatestimator import alsaseq import time import sync from alsain import alsaInput from beatestimator import Beatector # initialize ALSA alsaseq.client( 'Beatector', 1, 1, False ) alsain = alsaInput() estimator = Beatector() estimator.start() alsain.start() time.sleep(1) try: while True: time.sleep(1) except: sync.terminate.set() sync.queueEvent.set() estimator.join() alsain.join()
MUTE_GRP1_NOTE = 0x10 MUTE_GRP2_NOTE = 0x11 MUTE_GRP3_NOTE = 0x12 MUTE_GRP4_NOTE = 0x13 FX1_SEND = 0x00 FX2_SEND = 0x01 FX3_SEND = 0x02 FX4_SEND = 0x03 CHANNEL = 1 # connect to qu-16 usb #alsaseq.connectto( 0, 28, 0 ) alsaseq.client('quPy', 1, 1, False) #alsaseq.connectfrom( 0, 28, 0 ) #qu16_conn = alsaseq.connectto( 1, 11, 0 ) # qu16 #alsaseq.connectto( 1, 28, 0 ) # qu16 #sys.stderr.write(str(qu16_conn) + "\n") alsaseq.connectto(1, 129, 0) # midi monitor alsaseq.start() # send tap #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1, #0xB0 + (CHANNEL-1), 0x63, FX2_SEND)) ) #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1, #0xB0 + (CHANNEL-1), 0x62, 0x48)) ) #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1,
#!/usr/bin/python import sys import alsaseq import alsamidi alsaseq.client('ZynthianGUI', 0, 1, True) alsaseq.connectto( 0, 128, 0 ) alsaseq.connectto( 0, 130, 0 ) alsaseq.connectto( 0, 131, 0 ) alsaseq.start() # Instrument Select note=sys.argv[1] print "Program " + note event=alsamidi.pgmchangeevent(0, int(note)) alsaseq.output(event)
# def sigterm_handler(_signo, _stack_frame): # print "TERMINATE" # ============================================================================ # signal.signal(signal.SIGTERM, sigterm_handler) args = sys.argv[1:] args.append("-m") args.append('20:14:12:17:01:67') #args.append('20:14:12:17:02:47') params = parseArgs(args) # initialize ALSA alsaseq.client('LaserGun', 1, 1, False) if params.alsaOut is not None: (client, port) = params.alsaOut alsaseq.connectto(0, client, port) if params.alsaIn is not None: (client, port) = params.alsaIn alsaseq.connectfrom(0, client, port) # connect to bluetooth device sock = com.connect(params.btMAC) if not sock: logging.error('connection to laser gun failed') exit(2) listener = Listener(sock) scheduler = Scheduler(params)
# amidioffset.py - Tom Clayton # Connect input and out put to alsa midi streams and this program will # shift midi notes received by x notes. x is set with a command line # argument. x can be negative to shift down. import alsaseq import sys if len(sys.argv) > 1: offset = int(sys.argv[1]) else: print("Enter offset as command line argument.") sys.exit() alsaseq.client('Midi Offset', 1, 1, False) # alsaseq event: # (type, flags, tag, queue, time stamp, source, destination, data) # data = (channel, note, velocity, ??, ??) while True: if alsaseq.inputpending(): event = list(alsaseq.input()) if (event[0] == 6 or event[0] == 7): data = list(event[7]) data[1] += offset event[7] = tuple(data) alsaseq.output(event)
# def sigterm_handler(_signo, _stack_frame): # print "TERMINATE" # ============================================================================ # signal.signal(signal.SIGTERM, sigterm_handler) args = sys.argv[1:] args.append("-m") args.append('20:14:12:17:01:67') #args.append('20:14:12:17:02:47') params = parseArgs(args) # initialize ALSA alsaseq.client( 'LaserGun', 1, 1, False ) if params.alsaOut is not None: (client, port) = params.alsaOut alsaseq.connectto(0, client, port) if params.alsaIn is not None: (client, port) = params.alsaIn alsaseq.connectfrom(0, client, port) # connect to bluetooth device sock = com.connect(params.btMAC) if not sock: logging.error('connection to laser gun failed') exit(2) listener = Listener(sock) scheduler = Scheduler(params)
#!/usr/bin/env python3 # amiditimer.py - Tom Clayton # Connect input and output to alsa midi streams and this program will # send a message out and time how long it takes for it to return. import alsaseq import sys alsaseq.client('Midi Timer', 1, 1, True) # alsaseq event: # (type, flags, tag, queue, time stamp, source, destination, data) # data = (channel, note, velocity, start, duration) out_event = (6, 1, 0, 1, (0, 0), (0, 0), (0, 0), (0, 60, 127, 0, 0)) input("Midi Timer, connect then hit enter to start.") alsaseq.output(out_event) alsaseq.start() while True: if alsaseq.inputpending(): event = alsaseq.input() if event[0] == 6: print(event[4][1] / 1000000, " ms") break
# Script for Running the RNN Box system EMPI v2. import argparse # Grove from grove.i2c import Bus from grove.adc import ADC import RPi.GPIO as GPIO import grove_display from numpy import interp # ALSA MIDI import alsaseq import alsamidi # http://pp.com.mx/python/alsaseq/project.html # Setup for ALSA MIDI alsaseq.client('EMPIMIDI', 1, 1, False) # Setup for GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) parser = argparse.ArgumentParser(description='Interface for EMPI 2.0 using Grove shield and GPIO connection.') parser.add_argument('-m', '--mirror', dest='mirror', action="store_true", help="Mirror physical input on physical output for testing.") parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='Verbose, print input and output for testing.') parser.add_argument("--screen", dest="screen", default=False, action="store_true", help="Use OLED display for showing data.") parser.add_argument("--servo", dest="servo", default=False, action="store_true", help="Use the servomotor for embodied output") args = parser.parse_args() # Functions for sending and receving from levers. # Global vars for Grove board POTENTIOMETER_CHANNEL = 0 SERVO_CHANNEL = 5
#!/usr/bin/python import time import scipy, numpy, math # parsing import visual # visualisation import alsaseq, alsamidi # midi output alsaseq.client('Note Recogniser', 0, 1, False) rate = 8000 slen = 160 def miditof(x): return (440 / 32) * (2 ^ ((x - 9) / 12)) def ftomidi(f): return int((math.log(f / (440 / 32), 2) * 12) + 9) def PlayNote(note): alsaseq.output(alsamidi.noteonevent(0, note, 127)) class Event(object): pass
MUTE_GRP1_NOTE = 0x10 MUTE_GRP2_NOTE = 0x11 MUTE_GRP3_NOTE = 0x12 MUTE_GRP4_NOTE = 0x13 FX1_SEND = 0x00 FX2_SEND = 0x01 FX3_SEND = 0x02 FX4_SEND = 0x03 CHANNEL=1 # connect to qu-16 usb #alsaseq.connectto( 0, 28, 0 ) alsaseq.client( 'quPy', 1, 1, False ) #alsaseq.connectfrom( 0, 28, 0 ) #qu16_conn = alsaseq.connectto( 1, 11, 0 ) # qu16 #alsaseq.connectto( 1, 28, 0 ) # qu16 #sys.stderr.write(str(qu16_conn) + "\n") alsaseq.connectto( 1, 129, 0 ) # midi monitor alsaseq.start() # send tap #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1, #0xB0 + (CHANNEL-1), 0x63, FX2_SEND)) ) #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1, #0xB0 + (CHANNEL-1), 0x62, 0x48)) ) #alsaseq.output( (alsaseq.SND_SEQ_EVENT_NONREGPARAM, 1, 0, 1, (0,0), (0,0), (0,0), (CHANNEL-1,
# ZynAddSubFx has controllers that are not defined in GM. # # 1) Bandwidth (Sound control 6) (no. 75) # This increases or decreases the bandwidth of instruments. The default parameter is 64. # # 2) Modulation amplitude (Sound control 7) (no. 76) # This decreases the amplitude of modulators on ADsynth. The default parameter is 127. # # 3) Resonance Center Frequency (Sound control 8) (no. 77) # This changes the center frequency of the resonance. # # 4) Resonance Bandwidth (Sound control 9) (no. 78) # This changes the bandwidth of the resonance. # -------------------------------------- alsaseq.client("ZynthianGUI", 0, 1, True) alsaseq.connectto(0, 128, 0) alsaseq.connectto(0, 130, 0) alsaseq.connectto(0, 131, 0) alsaseq.start() time.sleep(1) # Instrument Select event = alsamidi.pgmchangeevent(0, 0) alsaseq.output(event) # Raw Note ON: alsaseq.output((6, 1, 0, 0, (0, 0), (0, 0), (0, 0), (0, 70, 127, 0, 100))) # Note ON Event
#!/usr/bin/env python3 # amidimonitor.py - Tom Clayton # Connect input to an alsa midi stream. This program will print note on # and note off messages recevied in hexidecimal. import alsaseq import sys alsaseq.client("Monitor", 1, 0, False) # alsaseq event: # (type, flags, tag, queue, time stamp, source, destination, data) # data = (channel, note, velocity, ??, ??) while True: if alsaseq.inputpending(): event = list(alsaseq.input()) if event[0] == 6: #Note on print(f'0x{0x90+event[7][0]:02x}', end=' ') print(f'0x{event[7][1]:02x}', end=' ') print(f'0x{event[7][2]:02x}') elif event[0] == 7: #Note off print(f'0x{0x80+event[7][0]:02x}', end=' ') print(f'0x{event[7][1]:02x}', end=' ') print(f'0x{event[7][2]:02x}')
import alsaseq, serial alsaseq.client( 'Recorder', 1, 0, True ) alsaseq.connectfrom( 1, 129, 0 ) alsaseq.start() events = [] EV_KEYDOWN = 6 EV_KEYUP = 7 s = serial.Serial("/dev/ttyUSB0", 115200) ch = 1 def sendmsg(chan,note,vel): print "msg going",chan,note onoff = 0x40 if note >= 0 else 0 note = abs(note) s.write(chr(0x80 | chan | onoff)) s.write(chr(0x60 | (note >> 4))) s.write(chr(0x50 | (note & 0xf))) s.write(chr(0x20 | (vel >> 4))) s.write(chr(0x10 | (vel & 0xf))) while 1: if alsaseq.inputpending(): ch = int(open("ch.txt", "r").read()) event = alsaseq.input() evtype = event[0] if evtype == EV_KEYDOWN: sendmsg(ch, event[7][1], event[7][2]) elif evtype == EV_KEYUP:
""" e = pyttsx.init() for v in e.getProperty('voices'): print v.id, v.languages, v.name e.setProperty('voice', 'english-us') e.say("If your system is already configured to load OSS drivers for your sound card then look at your current module loader configuration files. There will be entries for the OSS modules which will give you clues about which chipsets your sound cards have. Don't forget to disable these entries before reconfiguring things to load ALSA modules. This is a test. How are you doing?") e.runAndWait() exit() """ import alsaseq import time import math alsaseq.client('Click', 1, 1, True) alsaseq.connectto(1,128,0) class SongRhythm: beatsPerMeasure = 4 numberMeasures = 10 initialTempo = 180 finalTempo = 180 metronomeHits = [] # (<beat>, <soundfont num>) def totalBeatLength(self): return self.numberMeasures*self.beatsPerMeasure def measureBeatToBeat(self, measure, beat): return measure*self.beatsPerMeasure+beat def beatToSec(self, beat): beat = float(beat) return 60.0*(beat/self.initialTempo +
#--------------------------------------------------- def PrintDevices(self, InOrOut): if back_end == 'pypm': for loop in range(pypm.CountDevices()): interf,name,inp,outp,opened = pypm.GetDeviceInfo(loop) if ((InOrOut == INPUT) & (inp == 1) | (InOrOut == OUTPUT) & (outp ==1)): print loop, name," ", if (inp == 1): print "(input) ", else: print "(output) ", if (opened == 1): print "(opened)" else: print "(unopened)" print elif back_end == 'alsaseq': self.mDevIn = alsaseq.client('rtmid_alsaseq', 1, 1, False) self.mDevOut = self.mDevIn elif back_end == 'rtmidi': if InOrOut == INPUT: mt = rtmidi.MidiIn() else: mt = rtmidi.MidiOut() print('according to get_ports():') pn = mt.get_ports() for p in pn: print('name:' + p) print('according to get_port_name():') n = mt.get_port_count() for i in range(n): print('%d) %s' % (i, mt.get_port_name(i)))
return part def is_dissonant(note, memory): pitches = [False] * 5 pitches[2] = True for memory_note in memory: if memory_note and abs((note.pitch % 12) - (memory_note.pitch % 12)) <= 2: pitches[(memory_note.pitch % 12) - (note.pitch % 12)] = True # f**k science return ((pitches[0] and pitches[1] and pitches[2]) or (pitches[1] and pitches[2] and pitches[3]) or (pitches[2] and pitches[3] and pitches[4])) alsaseq.client('arp', 1, 1, False) alsaseq.connectto(1, 20, 0) def sigint_handler(signal, frame): finish() sys.exit(1) def finish(): curses.nocbreak() curses.echo() curses.endwin() print 'cleaning up' for channel in range(16): for pitch in range(128): alsaseq.output(alsamidi.noteoffevent(channel, pitch, 0))
import alsaseq, serial alsaseq.client('Recorder', 1, 0, True) alsaseq.connectfrom(1, 129, 0) alsaseq.start() events = [] EV_KEYDOWN = 6 EV_KEYUP = 7 s = serial.Serial("/dev/ttyUSB0", 115200) ch = 1 def sendmsg(chan, note, vel): print "msg going", chan, note onoff = 0x40 if note >= 0 else 0 note = abs(note) s.write(chr(0x80 | chan | onoff)) s.write(chr(0x60 | (note >> 4))) s.write(chr(0x50 | (note & 0xf))) s.write(chr(0x20 | (vel >> 4))) s.write(chr(0x10 | (vel & 0xf))) while 1: if alsaseq.inputpending(): ch = int(open("ch.txt", "r").read()) event = alsaseq.input() evtype = event[0] if evtype == EV_KEYDOWN:
def __init__(self, client_name="Zynthian_gui"): alsaseq.client(client_name,1,0,True) #alsaseq.connectto(0,130,0) alsaseq.start()
#!/usr/bin/python ## This is an example of a simple sound capture script. ## ## The script opens an ALSA pcm for sound capture. Set ## various attributes of the capture, and reads in a loop, ## Then prints the volume. ## ## To test it out, run it and shout at your microphone: import alsaaudio, time, audioop, scipy, visual, math import numpy as np import alsaseq import jack alsaseq.client('test', 1, 2, False) rate = 8000 slen = 160 freqs = np.fft.fftfreq(slen, 1.0 / rate) freqs = freqs[:len(freqs) / 2] def miditof(x): return (440 / 32) * (2 ^ ((x - 9) / 12)) def ftomidi(f): return int((math.log(f / (440 / 32), 2) * 12) + 9)
#!/usr/bin/python import time import scipy, numpy, math # parsing import visual # visualisation import alsaseq, alsamidi # midi output alsaseq.client( 'Note Recogniser', 0, 1, False ) rate = 8000 slen = 160 def miditof(x): return (440 / 32) * (2 ^ ((x - 9) / 12)); def ftomidi(f): return int((math.log(f / (440 / 32),2) * 12) + 9) def PlayNote(note): alsaseq.output(alsamidi.noteonevent( 0, note, 127 )) class Event(object): pass class Observable(object): def __init__(self):
#!/usr/bin/python ## This is an example of a simple sound capture script. ## ## The script opens an ALSA pcm for sound capture. Set ## various attributes of the capture, and reads in a loop, ## Then prints the volume. ## ## To test it out, run it and shout at your microphone: import alsaaudio, time, audioop, scipy, visual, math import numpy as np import alsaseq import jack alsaseq.client( 'test', 1, 2, False ) rate = 8000 slen = 160 freqs = np.fft.fftfreq(slen,1.0 / rate) freqs = freqs[:len(freqs) / 2] def miditof(x): return (440 / 32) * (2 ^ ((x - 9) / 12)); def ftomidi(f): return int((math.log(f / (440 / 32),2) * 12) + 9) def PlayNote(num): alsaseq.output( [6, 0, 0, 253, (0, 0), (129, 0), (131, 0), (0, num, 127, 0, 0)] )
# ZynAddSubFx has controllers that are not defined in GM. # # 1) Bandwidth (Sound control 6) (no. 75) # This increases or decreases the bandwidth of instruments. The default parameter is 64. # # 2) Modulation amplitude (Sound control 7) (no. 76) # This decreases the amplitude of modulators on ADsynth. The default parameter is 127. # # 3) Resonance Center Frequency (Sound control 8) (no. 77) # This changes the center frequency of the resonance. # # 4) Resonance Bandwidth (Sound control 9) (no. 78) # This changes the bandwidth of the resonance. #-------------------------------------- alsaseq.client('ZynthianGUI', 0, 1, True) alsaseq.connectto(0, 128, 0) alsaseq.connectto(0, 130, 0) alsaseq.connectto(0, 131, 0) alsaseq.start() time.sleep(1) # Instrument Select event = alsamidi.pgmchangeevent(0, 0) alsaseq.output(event) # Raw Note ON: alsaseq.output((6, 1, 0, 0, (0, 0), (0, 0), (0, 0), (0, 70, 127, 0, 100))) # Note ON Event
import alsamidi import alsaseq import logging from queue import Queue, Empty from pyseq.events import parse_event from pyseq.midiin import MidiInCtrl from pyseq.model import SequencerModel from pyseq.view import SequencerView FROM = [(28, 0), (32, 0)] TO = [(129, 0), (32, 0)] alsaseq.client("pyseq", 1, 1, 0) for midiin in FROM: alsaseq.connectfrom(0, midiin[0], midiin[1]) for midiout in TO: alsaseq.connectto(1, midiout[0], midiout[1]) def main(): logging.basicConfig(filename="debug.log", level=logging.DEBUG) midi_receiver = MidiInCtrl() view = SequencerView() sequencer = SequencerModel()
return timings if __name__ == "__main__": parser = argparse.ArgumentParser(PROC_NAME) parser.add_argument("-a", "--alsa-port", default=DEFAULT_TARGET_ALSA_PORT, type=str, help="Specify ALSA port to connect to, default: %s" % DEFAULT_TARGET_ALSA_PORT) parser.add_argument("-p", "--processor", type=str, help="Specify Sushi's processor to benchmark") parser.add_argument("-n", "--notes", type=int, nargs='+', default=[60], help="List of MIDI note numbers to send, default: %s" % DEFAULT_MIDI_NOTES) parser.add_argument("-d", "--duration", default=DEFAULT_NOTE_DURATION, type=float, help="Note duration in seconds, default: %s" % DEFAULT_NOTE_DURATION) args = parser.parse_args() grpc_helper = SushiRPChelper(args.processor) alsaseq.client(PROC_NAME, 0, 1, True) alsaseq.connectto(0, get_alsa_port_by_name(args.alsa_port), 0) alsaseq.start() grpc_helper.reset_timings() time.sleep(0.5) timings_no_load = grpc_helper.get_timings() print("Processor load without Note ONs: %s avg, %s max" % (timings_no_load.average, timings_no_load.max)) while (True): grpc_helper.reset_timings() for note in args.notes: alsaseq.output(noteonevent(0, note, 127)) time.sleep(args.duration) timings_end = grpc_helper.get_timings()