小星星简谱Python生成mid音频文件程序代码

from mido import Message, MidiFile, MidiTrack, MetaMessage

# 简谱音符到 MIDI 音符的映射
note_mapping = {
    1: 60,  # do
    2: 62,  # re
    3: 64,  # mi
    4: 65,  # fa
    5: 67,  # sol
    6: 69,  # la
    7: 71,   # si
    0: 0   # si
}

# 以字符串形式输入的简谱,只包含音符数字
simple_score_str = "1 1 5 5 6 6 5 0 0 4 4 3 3 2 2 1 0 0 5 5 4 4 3 3 2 0 0 5 5 4 4 3 3 2 0 0 1 1 5 5 6 6 5 0 0 4 4 3 3 2 2 1"
nums = simple_score_str.split()
simple_score = [(int(note), 1) for note in nums]  # 每个音符默认占一拍

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

# 设置速度为 120 BPM (500000 us per beat)
tempo = 500000
track.append(MetaMessage('set_tempo', tempo=tempo, time=0))

# 设置乐器(例如,钢琴,program=25)
track.append(Message('program_change', program=25, time=0))

# 时间变量,用于计算 MIDI 消息之间的时间间隔
current_time = 50

# 遍历简谱,将其转换为 MIDI 消息
for note, duration in simple_score:
    if note in note_mapping:
        midi_note = note_mapping[note]
        # 音符开启消息
        track.append(Message('note_on', note=midi_note, velocity=64, time=current_time))
        current_time = 0
        # 音符关闭消息
        track.append(Message('note_off', note=midi_note, velocity=127, time=duration * 480))  
    else:
        print(f"不支持的音符: {note}")

mid.save('0.mid')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EasySoft易软

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值