import tkinter as tk
import pygame.midi
import time
初始化 pygame.midi
pygame.midi.init()
获取 MIDI 输出设备
midi_out = pygame.midi.Output(0)
设置乐器为钢琴
midi_out.set_instrument(2)
def play_note(note_number, duration):
midi_out.note_on(note_number, 125)
pygame.time.wait(duration)
midi_out.note_off(note_number, 125)
root = tk.Tk()
root.title(“Digital Music Player”)
设置窗口大小
root.geometry(“400x300”)
创建文本框用于输入数字简谱
entry = tk.Entry(root)
entry.pack(pady=20)
def play_music():
music_notes = entry.get()
note_index = 0
base_duration = 500 # 基础音符时长
while note_index < len(music_notes):
note_char = music_notes[note_index]
duration = base_duration
if note_char == ‘-’:
time.sleep(0.5)
duration += base_duration
note_index += 1
continue
note_number = convert_note(note_char)
if note_number is not None:
play_note(note_number, duration)
note_index += 1
def convert_note(note_char):
note_mapping = {‘1’: 60, ‘2’: 62, ‘3’: 64, ‘4’: 65, ‘5’: 67, ‘6’: 69, ‘7’: 71}
return note_mapping.get(note_char)
创建播放按钮
play_button = tk.Button(root, text=“播放”, command=play_music)
play_button.pack()
root.mainloop()
关闭 MIDI 输出设备
midi_out.close()
pygame.midi.quit()