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')
小星星简谱Python生成mid音频文件程序代码
于 2025-04-20 07:57:16 首次发布