前言
上篇文章中,我介绍了如何通过编写爬虫来从 Free Midi Files Download 网站上爬取海量的MIDI数据。本篇文章介绍的是使用 pretty_midi 库来将MIDI文件转化成矩阵,并通过PyTorch的Dataset类来构建数据集,为之后的训练与测试中传入张量做准备。
实施过程
将MIDI文件转化成稀疏矩阵信息并存储
构建数据集的第一步是将MIDI文件中的音乐信息以(时间,音高)的矩阵形式提取出来,并以稀疏矩阵的形式来保存到npz文件中。pretty_midi库提供了在每一个音轨中遍历音符(Note),并得到每个音符的音高(pitch),音符开始时间(note_on)和音符结束时间(note_off),将开始和结束时间分别除以十六分音符的长度(60秒 / 120BPM / 4),就可以得到开始和结束的时间在矩阵中对应的位置。
代码详见 MusicCritique/util/data/create_database.py
def generate_nonzeros_by_notes():
root_dir = 'E:/merged_midi/'
midi_collection = get_midi_collection()
genre_collection = get_genre_collection()
for genre in genre_collection.find():
genre_name = genre['Name']
print(genre_name)
npy_file_root_dir = 'E:/midi_matrix/one_instr/' + genre_name + '/'
if not os.path.exists(npy_file_root_dir):
os.mkdir(npy_file_root_dir)
for midi in midi_collection.find({
'Genre': genre_name, 'OneInstrNpyGenerated': False}, no_cursor_timeout = True):
path = root_dir + genre_name + '/' + midi['md5'] + '.mid'
save_path = npy_file_root_dir + midi['md5'] + '.npz'
pm = pretty_midi.PrettyMIDI(path)
# segment_num = math.ceil(pm.get_end_time() / 8)
note_range = (24, 108)
# data = np.zeros((segment_num, 64, 84), np.bool_)
nonzeros = []
sixteenth_length = 60 / 120 / 4
for instr in pm.instruments:
if not instr.is_drum:
for note in instr.notes:
start = int(note.start / sixteenth_length)
end = int(note.end / sixteenth_length)
pitch = note.pitch
if pitch < note_range[0] or pitch >= note_range[1]:
continue
else:
pitch -=

本文详细介绍如何使用pretty_midi库将MIDI文件转换为矩阵形式,并利用PyTorch Dataset类构建音乐数据集,用于后续的机器学习模型训练。
最低0.47元/天 解锁文章
3058





