def light_all(midiout, color): # 14 = Set all leds message = mido.Message('sysex', data=default_header + [14] + [color]) midiout.send(message)
elif vol == 'p': stops = [4, 6, 16, 20, 33, 36, 45] elif vol == 'mf': stops = [4, 5, 6, 12, 15, 16, 19, 20, 32, 33, 35, 36, 45] elif vol == 'f': stops = [ 3, 4, 5, 6, 7, 11, 12, 15, 16, 19, 20, 27, 32, 33, 34, 35, 36, 38, 45 ] elif vol == 'ff': stops = [ 3, 4, 5, 6, 7, 8, 10, 11, 12, 15, 16, 17, 19, 20, 21, 22, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 40, 42, 45 ] elif vol == 't': stops = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20, 21, 22, 24, 25, 26, 27, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 45 ] organ = "MidiSport 1x1:MidiSport 1x1 MIDI 1 20:0" outport = mido.open_output(organ) msg = mido.Message('sysex', data=[0, 74, 79, 72, 65, 83, 127]) outport.send(msg) for i in stops: msg = mido.Message('program_change', channel=11, program=i) # print(msg) outport.send(msg)
num = 86 elif key == '=': # shift num = 87 return num num = 0 print("Please start typing! (ctrl-c or ctrl-d to quit, ctrl-g for bell)") while True: key = readchar.readchar() if (key == '\r'): print() else: if key != '\x07': # ignore bell for terminal sys.stdout.write(key) sys.stdout.flush() if key == '\x03' or key == '\x04': # ctrl-c or ctrl-d break num = charToTypewriter(key) if key in uppercase: # caps lock output.send(mido.Message('note_on', note=86, velocity=64)) output.send(mido.Message('note_on', note=num, velocity=64)) if key in uppercase: # shift to undo caps output.send(mido.Message('note_on', note=87, velocity=64))
def led_off(note): return mido.Message('note_on', note=note, velocity=0)
def led_red_blink(note): return mido.Message('note_on', note=note, velocity=4)
try: pos = scale_sharps.index(note_name) except ValueError: try: pos = scale_flats.index(note_name) except ValueError: return None n = pos - scale_sharps.index('A') if n < 0: n += 12 fn = 2 ** (n / 12) * A4freq m = int(12 * log(fn / A4freq, 2) + 69) return m note_duration = 1 * sec track.append(mido.MetaMessage('key_signature', key='C')) track.append(mido.MetaMessage('set_tempo', tempo=tempo)) # track.append(mido.Message('program_change', program=12, time=0)) t = 1 * sec track.append(mido.Message('note_on', note=60, velocity=127, time=int(t))) track.append(mido.Message('note_on', note=64, velocity=127, time=0)) track.append(mido.Message('note_off', note=60, velocity=127, time=int(note_duration))) track.append(mido.Message('note_off', note=64, velocity=127, time=0)) mid.save('new_song.mid')
def functionality(self, event): global mido_out global outport global o_up global o_down global reset global octave global counter key_on = event.char if (key_on == "+"): o_up = True o_down = False elif (key_on == "-"): o_down = True o_up = False elif (key_on == "*"): reset = True else: reset = False if (o_up == True and octave + 84 < 127): octave += 12 elif (o_up == False): octave = octave if (o_down == True and octave - 84 > -127): octave += -12 elif (o_down == False): octave = octave if (reset): octave = 0 #if (key_on == "q"): # outport.send(mido.Message('note_off', note=(60+octave), velocity=80)) # outport.close # break elif (key_on == "a"): outport.send(mido.Message('note_on', note=60 + octave, velocity=80)) elif (key_on == "w"): outport.send(mido.Message('note_on', note=61 + octave, velocity=80)) outport.close elif (key_on == "s"): outport.send(mido.Message('note_on', note=62 + octave, velocity=80)) outport.close elif (key_on == "e"): outport.send(mido.Message('note_on', note=63 + octave, velocity=80)) outport.close elif (key_on == "d"): outport.send(mido.Message('note_on', note=64 + octave, velocity=80)) outport.close elif (key_on == "f"): outport.send(mido.Message('note_on', note=65 + octave, velocity=80)) outport.close elif (key_on == "t"): outport.send(mido.Message('note_on', note=66 + octave, velocity=80)) outport.close elif (key_on == "g"): outport.send(mido.Message('note_on', note=67 + octave, velocity=80)) outport.close elif (key_on == "y"): outport.send(mido.Message('note_on', note=68 + octave, velocity=80)) outport.close elif (key_on == "h"): outport.send(mido.Message('note_on', note=69 + octave, velocity=80)) outport.close elif (key_on == "u"): outport.send(mido.Message('note_on', note=70 + octave, velocity=80)) outport.close elif (key_on == "j"): outport.send(mido.Message('note_on', note=71 + octave, velocity=80)) outport.close elif (key_on == "k"): outport.send(mido.Message('note_on', note=72 + octave, velocity=80)) outport.close counter = counter + 1 if (counter % 2 == 0): o_up = False o_down = False reset = False if (counter == 100): counter = 0
def sendMidi(self, _type, _channel, _note): msg = mido.Message(_type, channel=_channel, note=_note) print(msg) self.midi_port.send(msg)
def sendAfter(self, _type, _channel, _value): msg = mido.Message(_type, channel=_channel, value=_value) print(msg) self.midi_port.send(msg)
def send_note_off(note_name, name_to_midi, midi_outputs): msg = mido.Message("note_off", note=name_to_midi[note_name]) for o in midi_outputs: o.send(msg)
def run(self): pubsub = r.pubsub() pubsub.subscribe('KEYBOARD_UNBLOCK' ) # this message unblocks the Redis listen command pubsub.subscribe(self.onset) # this message triggers the note while self.running: for item in pubsub.listen(): if not self.running or not item['type'] == 'message': break if item['channel'] == self.onset: # the trigger may contain a value that should be mapped to MIDI val = item['data'] val = EEGsynth.rescale(val, slope=input_scale, offset=input_offset) val = EEGsynth.limit(val, 0, 127) val = int(val) if self.velocity == None: # use the value of the onset trigger velocity = val elif type(self.velocity) == str: velocity = float(r.get(self.velocity)) velocity = EEGsynth.rescale(velocity, slope=scale_velocity, offset=offset_velocity) velocity = EEGsynth.limit(velocity, 0, 127) velocity = int(velocity) else: velocity = self.velocity if type(self.pitch) == str: pitch = float(r.get(self.pitch)) pitch = EEGsynth.rescale(pitch, slope=scale_pitch, offset=offset_pitch) pitch = EEGsynth.limit(pitch, 0, 127) pitch = int(pitch) else: pitch = self.pitch if type(self.duration) == str: duration = float(r.get(self.duration)) duration = EEGsynth.rescale(duration, slope=scale_duration, offset=offset_duration) duration = EEGsynth.limit( duration, 0.05, float('Inf') ) # some minimal time is needed for the delay else: duration = self.duration if debug > 1: print '----------------------------------------------' print "onset ", self.onset, "=", val print "velocity", self.velocity, "=", velocity print "pitch ", self.pitch, "=", pitch print "duration", self.duration, "=", duration if midichannel is None: msg = mido.Message('note_on', note=pitch, velocity=velocity) else: msg = mido.Message('note_on', note=pitch, velocity=velocity, channel=midichannel) SendMessage(msg) if duration != None: # schedule a delayed MIDI message to be sent to switch the note off if midichannel is None: msg = mido.Message('note_on', note=pitch, velocity=0) else: msg = mido.Message('note_on', note=pitch, velocity=0, channel=midichannel) t = threading.Timer(duration, SendMessage, args=[msg]) t.start()
def send_note_on(note_name, name_to_midi, midi_outputs): msg = mido.Message("note_on", note=name_to_midi[note_name], velocity=DEFAULT_VELOCITY) for o in midi_outputs: o.send(msg)
def sustain_off(midi_outputs): msg = mido.Message("control_change", channel=0, control=64, value=0) for o in midi_outputs: o.send(msg)
def note_on(midiout, note, velocity=100): message = mido.Message('note_on', note=note, velocity=velocity) midiout.send(message)
def _update_led(self): msg = mido.Message('note_on', note=self._led_control_note, velocity=self._current_led_value) self._outport.send(msg)
import mido # Find Vibrance Port if os.name == "posix": # macOS or Linux systems # Just create a virtual port outport = mido.open_output("vibrance") elif os.name == "nt": # Windows system # Rely on external MIDI loopback software outport = mido.open_output("vibrance_loopback 4") else: raise ValueError("unsupported OS") try: while True: note = int(input("Note> ")) velocity = int(input("Vel> ")) msg = mido.Message("note_on") msg.note = note msg.velocity = velocity if outport.closed: break outport.send(msg) finally: outport.close()
def enable_thru(self, virtualPortName: str): fire = 'FL STUDIO FIRE.*' self.fireIn = self.connectMidiInPort(fire, self.messageCallbackAkai) if self.fireIn is None: return self.fireOut = self.connectMidiOutPort(fire) if self.fireOut is None: return self.virtualIn = mido.open_input(virtualPortName, virtual=True, callback=self.messageCallbackVirtual) if self.virtualIn is None: return self.virtualOut = mido.open_output(virtualPortName, virtual=True) if self.virtualOut is None: return print("connected {} - {}".format(fire, virtualPortName)) for row in range(4): for col in range(16): time.sleep(0.001) self.set_pad_color(row, col, 0x000000) i = 1 for height in self.buttons.values(): msg = mido.Message('control_change', channel=0, control=height, value=0) self.fireOut.send(msg) i += 1 self.map.reset(self.setColor) msgIsOn = mido.Message('control_change', control=self.buttons['PatternMetronome'], value=1) msgIsOff = mido.Message('control_change', control=self.buttons['PatternMetronome'], value=0) self.fireOut.send(msgIsOn) self.exampleScreen() self.character = 50 self.vals = [0] * 128 self.songpos = None print('Ready') try: if self.songpos is None: cnt = 0 isOn = False while True: cnt += 1 if cnt > 10: cnt = 0 isOn = not isOn if isOn: self.fireOut.send(msgIsOn) else: self.fireOut.send(msgIsOff) time.sleep(0.05) else: time.sleep(1) except Exception as e: print("connection lost", e.what())
def get_simple_midi(ticks_per_beat, state_array: List[MIDIState], tempo_factor: float, program=None): mid = mido.MidiFile(type=0, ticks_per_beat=ticks_per_beat) trk = mido.MidiTrack() mid.tracks.append(trk) trk.append( mido.Message('program_change', time=0, channel=0, program=program or 0)) current_tempo = int(state_array[0].tempo / tempo_factor) time_diff = 0 track_time = 0 def write_msg(name, **kwargs): nonlocal track_time, time_diff tmp_params = dict(time=time_diff, **kwargs) trk.append(mido.Message(name, time=time_diff, **kwargs)) track_time += time_diff time_diff = 0 return '%s{%s}' % (name, ', '.join('%s=%s' % (k, v) for k, v in tmp_params.items())) def set_tempo_msg(): nonlocal track_time, time_diff tmp_time_diff = time_diff trk.append(mido.MetaMessage('set_tempo', tempo=current_tempo)) track_time += time_diff time_diff = 0 return 'set_tempo{time=%d, tempo=%d}' % (tmp_time_diff, current_tempo) def print_time_msg(ticks, msg): beat = float(ticks) / input_midi.ticks_per_beat bar = int(beat / 4) beat = beat - bar * 4 print('%3d %4.2f %s' % (bar, beat, msg)) print_time_msg(0, ' START > ' + set_tempo_msg()) for i, s in enumerate(state_array): if len(s.notes) > 0: note_str = ' '.join('%3s' % midi_note_name(n.note) for n in s.notes) else: note_str = '--' msgs = list() if i == 0: prev_state = MIDIState(time=0, notes=set(), tempo=state_array[0].tempo) else: prev_state = state_array[i - 1] time_diff = s.time - prev_state.time if s.tempo != prev_state.tempo: current_tempo = int(s.tempo / tempo_factor) msgs.append(set_tempo_msg()) for n in prev_state.notes: if n not in s.notes: msgs.append( write_msg('note_off', note=n.note, velocity=n.volume, channel=0)) for n in s.notes: if n not in prev_state.notes: msgs.append( write_msg('note_on', note=n.note, velocity=n.volume, channel=0)) print_time_msg(s.time, '%7s > %s' % (note_str, ', '.join(msgs))) return mid
#time.sleep(1) #fs.noteoff(0, 60) #fs.noteoff(0, 72) #time.sleep(10) #new_process #heyo = '60' #generate_other_samples(heyo) while True: msg = mido.Message('note_on') for new_msg in inport.iter_pending(): msg = new_msg print(msg) # TODO: add multiprocessing code to make if hasattr(...) and elif hasattr(...) # contents running simultaneously (i.e. still playing while generating&loading new sound) if hasattr(msg, 'note'):
def as_mido_midi_msg(self): return mido.Message('note_off', channel=self.channel, note=self.pitch, velocity=self.velocity)
def features_to_midi(self, sounds, deltas): assert len(sounds) == len(deltas) track = mido.MidiTrack() tempo = mido.MetaMessage('set_tempo', tempo=self.tempo, time=0) time_signature = mido.MetaMessage( 'time_signature', numerator=self.numerator, denominator=self.denominator, clocks_per_click=self.clocks_per_click, notated_32nd_notes_per_beat=self.notated_32nd_notes_per_beat, time=0) track.append(tempo) track.append(time_signature) mask = sounds != self.pad_idx sounds = sounds[mask] deltas = deltas[mask] for sound, delta in zip(sounds, deltas): delta_idx = delta - 1 secs = self.idx_to_time[delta_idx] ticks = self.secs_to_ticks(secs) # note_on if sound < self.note_off_offset and sound >= self.note_on_offset: note = sound - self.note_on_offset note *= self.note_ratio msg = mido.Message('note_on', channel=0, note=note, velocity=self.vel_value, time=ticks) track.append(msg) # note_off elif sound < self.cc_offset: note = sound - self.note_off_offset note *= self.note_ratio msg = mido.Message('note_on', channel=0, note=note, velocity=0, time=ticks) track.append(msg) # control_change elif sound <= self.n_sounds: cc_idx = sound - self.cc_offset cc_control = self.cc_kept[cc_idx // 2] cc_value = self.cc_upper if cc_idx % 2 else self.cc_lower msg = mido.Message('control_change', channel=0, control=cc_control, value=cc_value, time=ticks) track.append(msg) end_of_track = mido.MetaMessage('end_of_track', time=ticks) track.append(end_of_track) midi = mido.MidiFile() midi.tracks.append(track) return midi
import re import threading import time import mido from six.moves import queue as Queue import tensorflow as tf # TODO(adarob): Use flattened imports. from magenta.common import concurrency from magenta.protobuf import music_pb2 _DEFAULT_METRONOME_TICK_DURATION = 0.05 _DEFAULT_METRONOME_PROGRAM = 117 # Melodic Tom _DEFAULT_METRONOME_MESSAGES = [ mido.Message(type='note_on', note=44, velocity=64), mido.Message(type='note_on', note=35, velocity=64), mido.Message(type='note_on', note=35, velocity=64), mido.Message(type='note_on', note=35, velocity=64), ] _DEFAULT_METRONOME_CHANNEL = 1 # 0-indexed. _DRUM_CHANNEL = 9 try: # The RtMidi backend is easier to install and has support for virtual ports. import rtmidi # pylint: disable=unused-import,g-import-not-at-top mido.set_backend('mido.backends.rtmidi') except ImportError: # Tries to use PortMidi backend by default.
def led_green_blink(note): return mido.Message('note_on', note=note, velocity=2)
def _handle_message(self, msg): """Handles a single incoming MIDI message. -If the message is being used as a signal, notifies threads waiting on the appropriate condition variable. -Adds the message to any capture queues. -Passes the message through to the output port, if appropriate. Args: msg: The mido.Message MIDI message to handle. """ # Notify any threads waiting for this message. msg_str = str(msg) for regex in list(self._signals): if regex.match(msg_str) is not None: self._signals[regex].notify_all() del self._signals[regex] # Call any callbacks waiting for this message. for regex in list(self._callbacks): if regex.match(msg_str) is not None: for fn in self._callbacks[regex]: threading.Thread(target=fn, args=(msg,)).start() del self._callbacks[regex] # Remove any captors that are no longer alive. self._captors[:] = [t for t in self._captors if t.is_alive()] # Add a different copy of the message to the receive queue of each live # capture thread. for t in self._captors: t.receive(msg.copy()) # Update control values if this is a control change message. if msg.type == 'control_change': if self._control_values.get(msg.control, None) != msg.value: tf.logging.debug('Control change %d: %d', msg.control, msg.value) self._control_values[msg.control] = msg.value # Pass the message through to the output port, if appropriate. if not self._passthrough: pass elif self._texture_type == TextureType.POLYPHONIC: if msg.type == 'note_on' and msg.velocity > 0: self._open_notes.add(msg.note) elif (msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0)): self._open_notes.discard(msg.note) self._outport.send(msg) elif self._texture_type == TextureType.MONOPHONIC: assert len(self._open_notes) <= 1 if msg.type not in ['note_on', 'note_off']: self._outport.send(msg) elif ((msg.type == 'note_off' or msg.type == 'note_on' and msg.velocity == 0) and msg.note in self._open_notes): self._outport.send(msg) self._open_notes.remove(msg.note) elif msg.type == 'note_on' and msg.velocity > 0: if self._open_notes: self._outport.send( mido.Message('note_off', note=self._open_notes.pop())) self._outport.send(msg) self._open_notes.add(msg.note)
def led_yellow_blink(note): return mido.Message('note_on', note=note, velocity=6)
def _send(self, msg_type, **kwargs): print("Sending %s" % msg_type) self.output.send(mido.Message(msg_type, channel=self.channel, **kwargs))
def to_midi(outfname): mf = mido.MidiFile() track = mido.MidiTrack() mf.tracks.append(track) wf = wave.open('a.wav', 'rb') data = wf.readframes(FRAMES_PER_BLOCK) sampleWidth = wf.getsampwidth() print("SWIDTH:%d" % sampleWidth) frameRate = wf.getframerate() #print(sampleWidth) fmt = { 1: "%db", 2: "<%dh", 4: "%<dl" }[sampleWidth] % (len(data) // sampleWidth) def to_array(block): if (block == None): return [] arr = np.array(list(struct.unpack(fmt, block))) return arr / 32768.0 active_notes = [0] * 128 deltaTime = 0 defTempo = 500000 totalTime = 0 track.append(mido.Message('program_change', program=0, time=0)) track.append(mido.MetaMessage('set_tempo', tempo=defTempo, time=0)) expectedLength = len(data) while data: if (len(data) != expectedLength): data = None continue arr = to_array(data) fft = abs(np.fft.rfft(arr)) #fft *= FRAMES_PER_BLOCK/np.linalg.norm(fft) frameTime = FRAMES_PER_BLOCK / frameRate peaks = argrelextrema(fft, np.greater)[0] / frameTime peaks = peaks[peaks > 80] peaks = peaks[peaks < 2000] for hump in peaks: if fft[int( hump * frameTime)] > 0.3 * np.linalg.norm(fft) + START_THRESHOLD: midi_index = int(12 * np.log2(hump / 440) + 69) if active_notes[midi_index] == 0: # Turn on the note #print("Turning on frequency %.2f"%hump) ve = int(min(fft[int(hump * frameTime)] // 6, 127)) active_notes[midi_index] = ve timeInTicks = int( mido.second2tick(deltaTime, mf.ticks_per_beat, defTempo)) track.append( mido.Message('note_on', note=midi_index, velocity=ve, time=timeInTicks)) deltaTime = 0 for i in range(len(active_notes)): freq = 2**((i - 69) / 12) * 440 index = int(np.round(freq * frameTime)) # A previous attempt at discerning the notes in the FT ## if fft[index] > START_THRESHOLD: ## if active_notes[i] == 0: ## # Turn on the note ## print("Turning on frequency %.2f"%freq) ## ve = int(min(fft[index]//8, 127)) ## active_notes[i] = ve ## timeInTicks = int(mido.second2tick(deltaTime, mf.ticks_per_beat, defTempo)) ## # TODO: Amplitude ## track.append(mido.Message('note_on', note=i, velocity=ve, time=timeInTicks)) ## deltaTime = 0 if fft[index] < 0.1 * np.linalg.norm(fft) + END_THRESHOLD: if active_notes[i] != 0: # Turn off the note ve = int(active_notes[i]) active_notes[i] = 0 timeInTicks = int( mido.second2tick(deltaTime, mf.ticks_per_beat, defTempo)) track.append( mido.Message('note_off', note=i, velocity=ve, time=timeInTicks)) deltaTime = 0 deltaTime += frameTime plot_data(arr, fft, frameTime) totalTime += frameTime # The time in the track if (totalTime % 2 < 0.001): print("Time elapsed: %.2f" % totalTime) #time.sleep(frameTime) data = wf.readframes(FRAMES_PER_BLOCK) for i in range(len(active_notes)): if active_notes[i] != 0: ve = active_notes[i] timeInTicks = int( mido.second2tick(deltaTime, mf.ticks_per_beat, defTempo)) track.append( mido.Message('note_off', note=i, velocity=ve, time=timeInTicks)) print("Finished playing track!") mf.save(outfname)
def MultiPianoRoll2Midi(file_name, bpm, pianoroll_dict): # 1.初始化 mid = mido.MidiFile() tracks = {} # 要保存的音轨信息 first_track = True midi_tempo = round(60000000 / bpm) # 这首歌的速度(每一拍多少微秒) # 2.保存音符 for key in pianoroll_dict: # print(key) # 2.1.定义音轨名称/使用乐器等 tracks[key] = mido.MidiTrack() # 定义新的音轨 mid.tracks.append(tracks[key]) # 在midi中添加这个音轨 if first_track: tracks[key].append( mido.MetaMessage('set_tempo', tempo=midi_tempo, time=0)) # 设置歌曲的速度 first_track = False tracks[key].append( mido.MetaMessage('track_name', name=pianoroll_dict[key]['name'], time=0)) # 这个音轨的名称 tracks[key].append( mido.Message('program_change', program=pianoroll_dict[key]['program'], time=0, channel=key)) # 这个音轨使用的乐器 # 2.2.从piano_dict中获取音符列表并转化为midi message的形式 note_list = [] for note_iterator in pianoroll_dict[key]['note']: note_list.append( ['on', note_iterator[0], note_iterator[1], note_iterator[2]]) note_list.append([ 'off', note_iterator[0] + note_iterator[3], note_iterator[1], note_iterator[2] ]) note_list = sorted(note_list, key=lambda item: item[1]) # 按照音符的时间排序 # 2.3.往tracks中保存这些音符 current_note_time = 0 for note_iterator in note_list: if note_iterator[0] == 'on': tracks[key].append( mido.Message( 'note_on', note=note_iterator[2], velocity=note_iterator[3], time=round(480 * (note_iterator[1] - current_note_time)), channel=key)) elif note_iterator[0] == 'off': tracks[key].append( mido.Message( 'note_off', note=note_iterator[2], velocity=note_iterator[3], time=round(480 * (note_iterator[1] - current_note_time)), channel=key)) current_note_time = note_iterator[1] # 3.保存这个midi文件 mid.save(file_name)
if __name__ == "__main__": # mid = mido.MidiFile(type=0) # track = mido.MidiTrack() # mid.tracks.append(track) # track.append(mido.Message('note_on', note=64, velocity=60, time=0)) # track.append(mido.Message('note_off', note=64, velocity=60, time=0)) # mid.save('a.mid') mid = MIDIFile('x.mid', overwrite=True) track = mido.MidiTrack() mid.tracks.append(track) track.append(mido.Message('note_on', note=64, velocity=60, time=0)) track.append(mido.Message('note_off', note=64, velocity=60, time=32)) # print(mid.tracks) mid.save() mid.print_midi() print("\n") mid.parse_midi() # mid.print_midi() # m = MIDIFile('x.mid', overwrite=True) # m.print_midi() # print("\n") # m.parse_midi()
def light_off(midiout, key): # 10 = Set leds in color code mode message = mido.Message('sysex', data=default_header + [10] + [key, 0]) midiout.send(message)