def test_running_status(self): return # Running doesn't work with PortMidi, so it's turned off. # Two note_on messages. (The second has no status byte, # so the last seen status byte is used instead.) a = mido.parse_all([0x90, 0x01, 0x02, 0x01, 0x02]) b = [Message('note_on', note=1, velocity=2)] * 2 self.assertEqual(a, b) # System common messages should cancel running status. # (0xf3 is 'songpos'. This should be 'song song=2' # followed by a stray data byte. a = mido.parse_all([0xf3, 2, 3]) b = [Message('song', song=2)] self.assertEqual(a, b)
def bruteforce_sound(path_to_wav, synth_def, params_def, target_score=50, pop_size=50, max_generations=100, mutation_rate=0.05, midi_channel=10, midi_device=None): global best_patch print('z', synth_def) # synth = SimpleCCPatch(midi_channel, synth_def, ['Feedback', 'Mix']) synth = SimpleCCPatch(midi_channel, synth_def, [ 'Algo', 'Ratio C', 'Ratio A', 'Ratio B1', 'Ratio B2', 'Harmonics', 'Detune', 'Feedback', 'Mix', 'A Level', 'B Level' ]) outport = mido.open_output(midi_device) comp = MFCCComparator(path_to_wav) length = comp.target_length gm = GeneticModel(pop_size, mutation_rate, epoch=30) gm.test_function = lambda S: try_speciman(synth, outport, midi_channel, comp, gm, S, length) for param in params_def: gm.add_param(param['name'], param['min'], param['max']) best_result = -1 for i in range(max_generations): print(f"Generation {i+1}/{max_generations}") generation = gm.iterate() # Send best patch for cmd in mido.parse_all(best_patch): outport.send(cmd)
def main(): """Parse a note_on msg and compare it to one created with Message().""" #message = mido.parse(b'\x90\x4c\x20') messages = mido.parse_all(b'\xB5\x8D\x80\x15\x40') for message in messages: print(message)
def generate_midi(self, filename, length=100, delay=96): output = MidiFile() byte_list = super().generate_obj_list(length) track = parse_all(byte_list) for message in track: message.time = delay output.tracks.append(self.metamessages) output.tracks.append(track) output.save(filename)
def wait_for_messages(self): while 1: socket_list = [self.sock] # Get the list sockets which are readable read_sockets, write_sockets, error_sockets = select.select( socket_list, [], [], 0) for sock in read_sockets: # incoming message from remote server if sock == self.sock: data = sock.recv(4096) if not data: print('\nDisconnected from chat server') sys.exit() else: # print data #sys.stdout.write(">" + str(binascii.unhexlify(data.decode())) + "<") #print("Received1: " + data.decode()) messages = str(data.decode()).split("m") if len(messages) >= 2: messages.pop(0) for message in messages: message_header = message[:1] message_body = message[2:] print(message) if message_header == "n": notes_hex = message_body notes_bin = bytearray.fromhex(notes_hex) notes_mido = mido.parse_all(notes_bin) print(notes_mido) if self.midi_ports != None: for note in notes_mido: if isinstance(note, Message): self.midi_ports_out.send(note) elif note.type == 'set_tempo': print( 'Tempo changed to {:.1f} BPM.' .format( tempo2bpm(note.tempo))) if self.midi_ports != None: msg = '' bytes = bytearray() for message in mido.ports.multi_receive(self.midi_ports, block=False): print('Sending: {}'.format(message)) bytes = bytes + message.bin() if bytes != b'': message = "mn=" + bytes.hex() #hex = "mn=803c00" #hex = "mn=803c00mn=903740" print("Sent: " + message) self.sock.send(message.encode())
def message(p1): """ This function will use the `mido` python midi module to generate a midi message (which can later be sent to a `mido` midi output) """ sysex=[0xf0] sysex.extend([0x41, 0x35, 0x00, 0x21, 0x20, 0x01]) sysex.extend(p1.bytes()) sysex.extend([0xf7]) return mido.parse_all(sysex)[0] if __name__ == '__main__': print 's\'all good, homie.'
def try_speciman(synth, midi_device, channel, comp, genetic_model, speciman, sample_length): global best_score global best_patch global best_count for (param, value) in zip(genetic_model.params, speciman.values): synth.set_param(param['key'], int(round(value))) # print(f'{param["key"]} = {int(round(value))}; ', end='') patch = synth.get_patch() # print('zxz', midi_device) outport = midi_device # outport = mido.open_output(midi_device) # send patch # midi.send(patch) # record wav # wav = record(sample_length, comp.sample_rate, 100) for cmd in mido.parse_all(patch): outport.send(cmd) wav = sd.rec(sample_length + 800, comp.sample_rate, channels=1) outport.send(mido.Message('note_on', channel=channel, note=48)) # time.sleep(.001) sd.wait() outport.send(mido.Message('note_off', channel=channel, note=48)) wav = trimpad(wav, 0.01, comp.target_length) normwav = normalize(wav) # wavfile.write(f'specimenx/feedback{speciman.values[0]}.wav', 48000, normwav) # wavfile.write(f'specimenx/orig{speciman.values[0]}.wav', 48000, wav) score = comp.compare_to(normwav, 48000) if score < best_score: wavfile.write(f'specimen/best{best_count}.wav', 48000, normwav) # wavfile.write(f'specimen/bestn{best_count}.wav', 48000, normwav) best_score = score best_patch = patch print(f'{best_count}. ', end='') best_count += 1 for (param, value) in zip(genetic_model.params, speciman.values): synth.set_param(param['key'], int(round(value))) print(f'{param["key"]} = {int(round(value))}; ', end='') print(' Score -> ', score) return score
else: return UnknownMsgType all_data_points = {} for i, track in enumerate(mid3.tracks): # print("--*--" * 20) # print('Track {}: {}'.format(i, track.name)) # print(track,dir(track)) len_msg = len(track) for msg in track: global_msg_count += 1 bytes_p = msg.bytes() decoded_msg = str(mido.parse_all(bytes_p)) # print(decoded_msg) msg_type = check_msg_type(msg=decoded_msg) if msg_type == MessageFormatter: identifier = "M" msg_repr = MessageFormatter(decoded_msg) elif msg_type == ResetTimerMsg: identifier = "R" msg_repr = ResetTimerMsg(decoded_msg) else: identifier = "U" msg_repr = UnknownMsgType() all_data_points["%s_%s" % (identifier, global_msg_count)] = msg_repr.arr
def test_undefined_realtime_inside_sysex(self): """Undefined realtime message inside sysex should ignored.""" messages = mido.parse_all([0xf0, 0, 0xf9, 0xfd, 0, 0xf7]) self.assertTrue(len(messages) == 1) self.assertTrue(messages[0].type == 'sysex')
def test_realtime_inside_sysex(self): """Realtime message inside sysex should be delivered first.""" messages = mido.parse_all([0xf0, 0, 0xfb, 0, 0xf7]) self.assertTrue(len(messages) == 2) self.assertTrue(messages[0].type == 'continue') self.assertTrue(messages[1].type == 'sysex')
def test_undefined_messages(self): """The parser should ignore undefined status bytes and sysex_end.""" messages = mido.parse_all([0xf4, 0xf5, 0xf7, 0xf9, 0xfd]) self.assertTrue(messages == [])
def test_one_byte_message(self): """Messages that are one byte long should not wait for data bytes.""" messages = mido.parse_all([0xf6]) # Tune request. self.assertTrue(len(messages) == 1) self.assertTrue(messages[0].type == 'tune_request')
def test_parse_stray_status_bytes(self): """The parser should ignore stray status bytes.""" ret = mido.parse_all(b'\x90\x90\xf0') self.assertTrue(ret == [])
def test_parse_stray_data(self): """The parser should ignore stray data bytes.""" ret = mido.parse_all(b'\x20\x30') self.assertTrue(ret == [])