在Python MIDI MIDO读取/保存文件中转换时间/刻度

时间:2017-08-19 13:37:04

标签: midi mido

以下程序使用MIDO来阅读' g1.mid'然后将其保存到' g1_new.mid'。我的问题是:在阅读文件时,' msg.time'是一个浮点值,但在保存文件时,'时间在消息'是一个整数形式。我们如何转换' msg.time'在邮件中打勾'在这种情况下?

from mido import MidiFile 
from mido import Message, MidiTrack

mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

for msg in MidiFile('g1.mid'):
    if (not msg.is_meta):
        if (msg.type == 'note_on'):
            # how to convert msg.time to tick to fill in '?'
            track.append(Message('note_on', note=msg.note, velocity=msg.velocity, time=?))
        elif (msg.type == 'note_off'):
            # how to convert msg.time to tick to fill in '?'
            track.append(Message('note_off', note=msg.note, velocity=msg.velocity, time=?))
        elif (msg.type == 'program_change'):
            track.append(Message('program_change', program=msg.program, channel=msg.channel))

mid.save('g1_new.mid')

注意:这段代码是关于音乐生成的项目。

1 个答案:

答案 0 :(得分:0)

当您遍历MidiFile对象本身时,时间戳会被显式转换:

class MidiFile(object):
    ...
    def __iter__(self):
        ...
        tempo = DEFAULT_TEMPO
        for msg in merge_tracks(self.tracks):
            # Convert message time from absolute time
            # in ticks to relative time in seconds.
            if msg.time > 0:
                delta = tick2second(msg.time, self.ticks_per_beat, tempo)
            else:
                delta = 0

            yield msg.copy(time=delta)

            if msg.type == 'set_tempo':
                tempo = msg.tempo

所以直接迭代mid.tracks(或在合并的轨道上)。