import numpy as np
import pygame
import tkinter as tk
from tkinter import messagebox, Menu
import random
pygame.init()
pygame.mixer.init()
NOTES = {
'1.': 130.81, '2.': 146.83, '3.': 164.81, '4.': 174.61, '5.': 196.00, '6.': 220.00, '7.': 246.94,
'1': 261.63, '2': 293.66, '3': 329.63, '4': 349.23, '5': 392.00, '6': 440.00, '7': 493.88,
'1*': 523.25, '2*': 587.33, '3*': 659.25, '4*': 698.46, '5*': 783.99, '6*': 880.00, '7*': 987.77,
'-': 0
}
DEFAULT_SCORE = """5-351*--76-1*-5---5-123-212----5-351*--76-1*-5---5-234--7.1----6-1*-1*---7-671*---671*665312----5-351*--76-1*-5---5-234--7.1------"""
DEFAULT_SPEED = 1.0
def generate_sound(freq, duration=0.3):
if freq == 0: return None
t = np.linspace(0, duration, int(44100*duration))
mono = np.sin(2*np.pi*freq*t)
stereo = np.column_stack((mono, mono))
return pygame.sndarray.make_sound((stereo*32767).astype(np.int16))
def parse_score(score_text):
notes = []
i = 0
n = len(score_text)
while i < n:
char = score_text[i]
if char == '-':
start = i
while i < n and score_text[i] == '-':
i += 1
notes.append('-'*(i-start))
else:
start = i
if char in '1234567':
i += 1
if i < n and score_text[i] in ('.', '*'):
i += 1
notes.append(score_text[start:i])
return notes
def play_sequence():
try:
speed = float(speed_entry.get()) if speed_entry.get() else DEFAULT_SPEED
score_text = entry.get("1.0", tk.END).strip() or DEFAULT_SCORE
score_text = ''.join([c for c in score_text if c in '1234567.*-'])
notes = parse_score(score_text)
valid_notes = []
for note in notes:
if note.startswith('-'):
valid_notes.append(note)
else:
note_upper = note.upper()
if note_upper in NOTES:
valid_notes.append(note_upper)
else:
print(f"无效音符: {note}")
if not valid_notes:
messagebox.showwarning("提示", "无有效音符!")
return
duration_base = 0.3 * speed
for note in valid_notes:
if note.startswith('-'):
length = len(note)
pygame.time.delay(int(length * duration_base * 1000))
else:
freq = NOTES[note]
sound = generate_sound(freq, duration_base)
if sound:
sound.play()
pygame.time.delay(int(duration_base * 1000))
except ValueError:
messagebox.showerror("错误", "速度值必须为数字(如0.5-2.0)")
except Exception as e:
messagebox.showerror("错误", f"播放失败:{str(e)}")
def create_text_right_click_menu(text_widget):
right_click_menu = Menu(root, tearoff=0)
right_click_menu.add_command(label="全选", command=lambda: text_widget.tag_add(tk.SEL, "1.0", tk.END))
right_click_menu.add_command(label="复制", command=lambda: text_widget.event_generate("<>"))
right_click_menu.add_command(label="粘贴", command=lambda: text_widget.event_generate("<>"))
right_click_menu.add_command(label="剪切", command=lambda: text_widget.event_generate("<>"))
right_click_menu.add_separator()
right_click_menu.add_command(label="删除", command=lambda: text_widget.delete(tk.SEL_FIRST, tk.SEL_LAST))
def show_menu(event):
try:
right_click_menu.tk_popup(event.x_root, event.y_root)
finally:
right_click_menu.grab_release()
text_widget.bind("", show_menu)
text_widget.bind("", show_menu)
root = tk.Tk()
root.title("简谱播放器(文本框速度输入)")
root.geometry("800x500")
speed_frame = tk.Frame(root)
speed_frame.pack(pady=10, padx=20, fill=tk.X)
speed_label = tk.Label(speed_frame, text="播放速度(0.5-2.0倍):")
speed_label.pack(side=tk.LEFT, padx=5)
speed_entry = tk.Entry(speed_frame, font=('Arial', 10), width=8)
speed_entry.insert(0, str(DEFAULT_SPEED))
speed_entry.pack(side=tk.LEFT, padx=5)
speed_hint = tk.Label(speed_frame, text="如:1.0为正常速度, 0.5为快2倍")
speed_hint.pack(side=tk.LEFT, padx=10)
label = tk.Label(root, text="输入简谱(无空格,-表示休止符,.低音*高音,支持右键菜单):")
label.pack(pady=5)
a = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "1", "2", "3", "4", "5", "6", "7", "1*", "2*", "3*", "4*", "5*", "6*", "7*"]
b = ["", "-", "--"]
def generate_random_notes():
random_notes = []
for _ in range(110):
random_note = random.choice(a) + random.choice(b)
random_notes.append(random_note)
entry.delete("1.0", tk.END)
entry.insert(tk.END, "".join(random_notes))
entry = tk.Text(root, font=('Arial', 12), width=60, height=12, wrap=tk.WORD)
entry.pack(pady=10, padx=20)
entry.insert(tk.END, DEFAULT_SCORE)
generate_button = tk.Button(root, text="随机谱曲", command=generate_random_notes)
generate_button.pack(pady=25, padx=20)
create_text_right_click_menu(entry)
play_btn = tk.Button(root, text="开始播放", command=play_sequence,
font=('Arial', 12), bg="#4CAF50", fg="white", width=20)
play_btn.pack(pady=20)
root.mainloop()
pygame.quit()