How to use the mido.MetaMessage function in mido

To help you get started, we’ve selected a few mido examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CANToolz / CANToolz / examples / MIDI_to_CAN_example / CANMusic.py View on Github external
CANEngine = CANSploit()
CANEngine.load_config("CANToolz_config/BMW_F10_MUSIC.py")
CANEngine.start_loop()
index = CANEngine.find_module('ecu_controls')
index2 = CANEngine.find_module('analyze')
while not CANEngine.status_loop:
    time.sleep(0.000001)

try:
    # CHANGE PATH TO PLAYER AND TRACK HERE!!!!!!
    prc = Popen("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe CANToolz_config/track.mp3")
    time.sleep(0.2)
    for message in MidiFile('CANToolz_config/BMW.mid'):
        time.sleep(message.time)
        if not isinstance(message, MetaMessage) and message.type == 'note_on':
            print(str(message.note))
            CANEngine.call_module(index, str(message.note))
        print(CANEngine.call_module(index2, "p"))
except KeyboardInterrupt:
    print("gg bb, do not press ctrl-c again!")
except:
    print("gg hf")

CANEngine.stop_loop()
CANEngine.engine_exit()

while CANEngine.status_loop:
    time.sleep(0.000001)
github HaloOrangeWang / NoiseMaker / MakerSrc / interfaces / midi.py View on Github external
def multi_pianoroll_to_midi(file_name, bpm, pianoroll_dic):
    # 1.初始化
    mid = mido.MidiFile()
    tracks = {}  # 要保存的音轨信息
    first_track = True
    midi_tempo = round(60000000 / bpm)  # 这首歌的速度(每一拍多少微秒)
    # 2.保存音符
    for key in pianoroll_dic:
        # 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_dic[key]['name'], time=0))  # 这个音轨的名称
        tracks[key].append(mido.Message('program_change', program=pianoroll_dic[key]['program'], time=0, channel=key))  # 这个音轨使用的乐器
        # 2.2.从piano_dict中获取音符列表并转化为midi message的形式
        note_list = []
        for note_it in pianoroll_dic[key]['note']:
            note_list.append(['on', note_it[0], note_it[1], note_it[2]])
            note_list.append(['off', note_it[0] + note_it[3], note_it[1], note_it[2]])
        note_list = sorted(note_list, key=lambda item: item[1])  # 按照音符的时间排序
        # 2.3.往tracks中保存这些音符
        current_note_time = 0
        for note_it in note_list:
            if note_it[0] == 'on':
                tracks[key].append(mido.Message('note_on', note=note_it[2], velocity=note_it[3], time=round(480 * (note_it[1] - current_note_time)), channel=key))
            elif note_it[0] == 'off':
                tracks[key].append(mido.Message('note_off', note=note_it[2], velocity=note_it[3], time=round(480 * (note_it[1] - current_note_time)), channel=key))
            current_note_time = note_it[1]
    # 3.保存这个midi文件
github sky-music / sky-python-music-sheet-maker / src / skymusic / old_song.py View on Github external
track = mido.MidiTrack()
        mid.tracks.append(track)

        try:
            tempo = mido.bpm2tempo(self.midi_bpm)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))
        except ValueError:
            print("\n***Warning: invalid tempo passed to MIDI renderer. Using 120 bpm instead.\n")
            tempo = mido.bpm2tempo(120)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))

        sec = mido.second2tick(1, ticks_per_beat=mid.ticks_per_beat, tempo=tempo)  # 1 second in ticks
        note_ticks = self.midi_note_duration * sec * 120 / self.midi_bpm  # note duration in ticks

        try:
            track.append(mido.MetaMessage('key_signature', key=self.midi_key))
        except ValueError:
            print("\n***Warning: invalid key passed to MIDI renderer. Using C instead.\n")
            track.append(mido.MetaMessage('key_signature', key='C'))
        try:
            track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
        except ValueError:
            print("\n***Warning: invalid instrument passed to MIDI renderer. Using piano instead.\n")
            track.append(mido.Message('program_change', program=1, time=0))

        for line in self.lines:
            if len(line) > 0:
                if line[0].get_type() != 'voice':
                    instrument_index = 0
                    for instrument in line:
                        instrument.set_index(instrument_index)
                        instrument_render = instrument.render_in_midi(note_duration=note_ticks,
github sky-music / sky-python-music-sheet-maker / src / skymusic / old_song.py View on Github external
def write_midi(self):
        global no_mido_module

        if no_mido_module:
            print("\n***WARNING: MIDI was not created because mido module was not found. ***\n")
            return None

        mid = mido.MidiFile(type=0)
        track = mido.MidiTrack()
        mid.tracks.append(track)

        try:
            tempo = mido.bpm2tempo(self.midi_bpm)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))
        except ValueError:
            print("\n***Warning: invalid tempo passed to MIDI renderer. Using 120 bpm instead.\n")
            tempo = mido.bpm2tempo(120)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))

        sec = mido.second2tick(1, ticks_per_beat=mid.ticks_per_beat, tempo=tempo)  # 1 second in ticks
        note_ticks = self.midi_note_duration * sec * 120 / self.midi_bpm  # note duration in ticks

        try:
            track.append(mido.MetaMessage('key_signature', key=self.midi_key))
        except ValueError:
            print("\n***Warning: invalid key passed to MIDI renderer. Using C instead.\n")
            track.append(mido.MetaMessage('key_signature', key='C'))
        try:
            track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
        except ValueError:
github sky-music / sky-python-music-sheet-maker / src / skymusic / renderers / song_renderers.py View on Github external
except TypeError:
            print("\n***Warning: Invalid music key passed to the MIDI renderer: using C instead\n")
            self.midi_key = 'C'


        mid = mido.MidiFile(type=0)
        track = mido.MidiTrack()
        mid.tracks.append(track)

        try:
            tempo = mido.bpm2tempo(self.midi_bpm)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))
        except ValueError:
            print("\n***Warning: invalid tempo passed to MIDI renderer. Using 120 bpm instead.\n")
            tempo = mido.bpm2tempo(120)
            track.append(mido.MetaMessage('set_tempo', tempo=tempo))

        sec = mido.second2tick(1, ticks_per_beat=mid.ticks_per_beat, tempo=tempo)  # 1 second in ticks
        note_ticks = self.midi_note_duration * sec * 120 / self.midi_bpm  # note duration in ticks

        try:
            track.append(mido.MetaMessage('key_signature', key=self.midi_key))
        except ValueError:
            print("\n***Warning: invalid key passed to MIDI renderer. Using C instead.\n")
            track.append(mido.MetaMessage('key_signature', key='C'))
        try:
            track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
        except ValueError:
            print("\n***Warning: invalid instrument passed to MIDI renderer. Using piano instead.\n")
            track.append(mido.Message('program_change', program=1, time=0))

        instrument_renderer = InstrumentMIDIRenderer(self.locale)
github Conchylicultor / MusicGenerator / deepmusic / midireader.py View on Github external
pass  # TODO
            else:
                err_msg = 'Header track contains unsupported meta-message type ({})'.format(message.type)
                raise MidiInvalidException(err_msg)

        for i, track in enumerate(midi_data.tracks[1:]):  # We ignore the tempo map
            i += 1  # Warning: We have skipped the track 0 so shift the track id
            #tqdm.write('Track {}: {}'.format(i, track.name))

            new_track = music.Track()

            buffer_notes = []  # Store the current notes (pressed but not released)
            abs_tick = 0  # Absolute nb of ticks from the beginning of the track
            for message in track:
                abs_tick += message.time
                if isinstance(message, mido.MetaMessage):  # Lyrics, track name and other meta info
                    if message.type in MidiReader.META_INFO_TYPES:
                        pass
                    elif message.type in MidiReader.META_TEMPO_TYPES:
                        # TODO: Could be just a warning
                        raise MidiInvalidException('Track {} should not contain {}'.format(i, message.type))
                    else:
                        err_msg = 'Track {} contains unsupported meta-message type ({})'.format(i, message.type)
                        raise MidiInvalidException(err_msg)
                    # What about 'sequence_number', cue_marker ???
                else:  # Note event
                    if message.type == 'note_on' and message.velocity != 0:  # Note added
                        new_note = music.Note()
                        new_note.tick = abs_tick
                        new_note.note = message.note
                        if message.channel+1 != i and message.channel+1 != MidiReader.MIDI_CHANNEL_DRUMS:  # Warning: Mido shift the channels (start at 0) # TODO: Channel management for type 0
                            raise MidiInvalidException('Notes belong to the wrong tracks ({} instead of {})'.format(i, message.channel))  # Warning: May not be an error (drums ?) but probably
github sky-music / sky-python-music-sheet-maker / src / skymusic / renderers / song_renderers / midi_sr.py View on Github external
def write_header(self, mid, track, tempo):
                
        track.append(mido.MetaMessage('set_tempo', tempo=tempo))

        try:
            track.append(mido.MetaMessage('key_signature', key=self.midi_key))
        except ValueError:
            print("\n***ERROR: invalid key passed to MIDI renderer. Using C instead.")
            track.append(mido.MetaMessage('key_signature', key='C'))
        try:
            track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
        except ValueError:
            print("\n***ERROR: invalid instrument passed to MIDI renderer. Using piano instead.")
            track.append(mido.Message('program_change', program=1, time=0))
github aubio / aubio / python / demos / demo_wav2midi.py View on Github external
tolerance = 0.8

notes_o = notes("default", win_s, hop_s, samplerate)

print("%8s" % "time","[ start","vel","last ]")

# create a midi file
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

ticks_per_beat = mid.ticks_per_beat # default: 480
bpm = 120 # default midi tempo

tempo = bpm2tempo(bpm)
track.append(MetaMessage('set_tempo', tempo=tempo))
track.append(MetaMessage('time_signature', numerator=4, denominator=4))

def frames2tick(frames, samplerate=samplerate):
    sec = frames / float(samplerate)
    return int(second2tick(sec, ticks_per_beat, tempo))

last_time = 0

# total number of frames read
total_frames = 0
while True:
    samples, read = s()
    new_note = notes_o(samples)
    if (new_note[0] != 0):
        note_str = ' '.join(["%.2f" % i for i in new_note])
        print("%.6f" % (total_frames/float(samplerate)), new_note)