python语言MIDI简谱播放器代码

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

易软科技(河源)有限公司

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

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

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

打赏作者

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

抵扣说明:

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

余额充值