Python编曲实践(六):将MIDI文件转化成矩阵,继承PyTorch的Dataset类来构建数据集(附数据集网盘下载链接)

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

前言

上篇文章中,我介绍了如何通过编写爬虫来从 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 -= 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值