在 Python MIDI MIDO read/save 文件中转换 time/tick
Convert time/tick in Python MIDI MIDO read/save file
以下程序使用MIDO读取'g1.mid'然后保存到'g1_new.mid'。我的问题是:在读取文件时,'msg.time'是一个float值,但在保存文件时,'time in Message'是一个整数,tick。在这种情况下,我们如何将 'msg.time' 转换为 'tick in message'?
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')
注意:这段代码在一个关于音乐生成的项目中。
当您遍历 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
(或合并的轨道)。
以下程序使用MIDO读取'g1.mid'然后保存到'g1_new.mid'。我的问题是:在读取文件时,'msg.time'是一个float值,但在保存文件时,'time in Message'是一个整数,tick。在这种情况下,我们如何将 'msg.time' 转换为 'tick in message'?
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')
注意:这段代码在一个关于音乐生成的项目中。
当您遍历 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
(或合并的轨道)。