-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolyPy – Multi-Track Audio Engine (code).py
More file actions
346 lines (303 loc) · 19.9 KB
/
PolyPy – Multi-Track Audio Engine (code).py
File metadata and controls
346 lines (303 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import winsound
import threading
import time
import json
import numpy as np
import wave
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# --- TŁUMACZENIA ---
LANGS = {
"PL": {
"title": "PolyPy – Multi-Track Audio Engine",
"file": "Plik", "load": "Wczytaj projekt JSON", "save": "Zapisz projekt JSON",
"import": "Importuj z Tekstu", "export": "Eksportuj tę ścieżkę (tekst)",
"wav": "Eksportuj projekt do .WAV", "instrument": "Instrument", "settings": "Ustawienia",
"prev": "<", "next": ">", "new": "+ NOWA ŚCIEŻKA", "delete": "- USUŃ", "track": "Ścieżka",
"bpm": "BPM", "octave": " Oktawa", "time": "ms", "add": "DODAJ NUTĘ", "del_note": "USUŃ NUTĘ",
"col_n": "Nuta", "col_d": "Czas", "col_i": "Instrument",
"play": "GRAJ WSZYSTKO", "stop": "STOP", "clear": "WYCZYŚĆ",
"theme": "Motyw", "dark": "Ciemny", "light": "Jasny", "lang": "Język", "apply": "Zastosuj",
"edit": "Edycja", "copy": "Kopiuj ścieżkę", "paste": "Wklej ścieżkę", "oct_up": "Cała ścieżka +1 oktawa", "oct_down": "Cała ścieżka -1 oktawa",
"info_menu": "Informacje", "info_title": "Informacje o programie",
"info_msg": "PolyPy v0.8 Alpha\n\nTo jest wersja wczesnego dostępu. Program jest wciąż rozwijany, więc mogą występować błędy w generowaniu dźwięku lub interfejsie.\n\nDziękujemy za testowanie!"
},
"EN": {
"title": "PolyPy – Multi-Track Audio Engine",
"file": "File", "load": "Load JSON", "save": "Save JSON",
"import": "Import from Text", "export": "Export track (text)",
"wav": "Export to .WAV", "instrument": "Instrument", "settings": "Settings",
"prev": "<", "next": ">", "new": "+ NEW TRACK", "delete": "- REMOVE", "track": "Track",
"bpm": "BPM", "octave": " Octave", "time": "ms", "add": "ADD NOTE", "del_note": "REMOVE NOTE",
"col_n": "Note", "col_d": "Duration", "col_i": "Instrument",
"play": "PLAY ALL", "stop": "STOP", "clear": "CLEAR",
"theme": "Theme", "dark": "Dark", "light": "Light", "lang": "Language", "apply": "Apply",
"edit": "Edit", "copy": "Copy track", "paste": "Paste track", "oct_up": "Whole track +1 Octave", "oct_down": "Whole track -1 Octave",
"info_menu": "Information", "info_title": "Program information",
"info_msg": "PolyPy v0.8 Alpha\n\nThis is an early access version. The program is still under development, so bugs in audio generation or UI may occur.\n\nThank you for testing!"
}
}
NOTE_FREQ_BASE = {'C': 261.63, 'C#': 277.18, 'D': 293.66, 'D#': 311.13, 'E': 329.63, 'F': 349.23, 'F#': 369.99, 'G': 392.00, 'G#': 415.30, 'A': 440.00, 'A#': 466.16, 'B': 493.88, 'P': 0}
OCTAVE_MULTIPLIERS = {1:0.125, 2:0.25, 3:0.5, 4:1.0, 5:2.0, 6:4.0, 7:8.0}
SAMPLERATE = 44100
class Note:
def __init__(self, names=['C'], octaves=[4], duration_ms=400, volume=100, instrument="Beep (classic)"):
self.names, self.octaves, self.duration_ms, self.volume, self.instrument = names, octaves, duration_ms, volume, instrument
def frequencies(self):
return [int(NOTE_FREQ_BASE.get(n, 0) * OCTAVE_MULTIPLIERS.get(o, 1)) if n != 'P' else 0 for n, o in zip(self.names, self.octaves)]
def to_dict(self):
return {'names': list(self.names), 'octaves': list(self.octaves), 'duration_ms': self.duration_ms, 'volume': self.volume, 'instrument': self.instrument}
@staticmethod
def from_dict(d, default_inst="Beep (classic)"):
names = d.get('names', [d.get('name', 'C')])
octaves = d.get('octaves', [d.get('octave', 4)])
return Note(names, octaves, d.get('duration_ms', 400), d.get('volume', 100), d.get('instrument', default_inst))
class PolyPy(tk.Tk):
def __init__(self):
super().__init__()
self.current_lang, self.current_theme = "PL", "dark"
self.tracks, self.current_track_index, self.playing = [[]], 0, False
self.bpm, self.current_instrument = tk.IntVar(value=120), tk.StringVar(value="Beep (classic)")
self.clipboard = []
self.fig = Figure(figsize=(5, 2.5), dpi=90)
self.ax_fft = self.fig.add_subplot(121)
self.ax_wave = self.fig.add_subplot(122)
self.setup_ui()
def setup_ui(self):
for widget in self.winfo_children(): widget.destroy()
l = LANGS[self.current_lang]
self.title(l["title"]); self.geometry("1100x950")
self.setup_menu(l)
bg_col = "#2d2d2d" if self.current_theme == "dark" else "#f0f0f0"
# Nawigacja
nav = tk.Frame(self, bg=bg_col); nav.pack(fill='x', padx=10, pady=10)
ttk.Button(nav, text=l["prev"], width=3, command=self.prev_track).pack(side='left')
self.track_info_label = ttk.Label(nav, text="", font=('Arial', 10, 'bold'))
self.track_info_label.pack(side='left', padx=15)
ttk.Button(nav, text=l["next"], width=3, command=self.next_track).pack(side='left')
ttk.Separator(nav, orient='vertical').pack(side='left', fill='y', padx=10)
ttk.Button(nav, text=l["new"], command=self.add_new_track).pack(side='left', padx=2)
ttk.Button(nav, text=l["delete"], command=self.remove_current_track).pack(side='left', padx=2)
top = tk.Frame(self, bg=bg_col); top.pack(fill='x', padx=10, pady=5)
ttk.Label(top, text=f"{l['bpm']}:").pack(side='left')
ttk.Spinbox(top, from_=20, to=300, textvariable=self.bpm, width=5).pack(side='left', padx=5)
self.note_var = tk.StringVar(value='C')
ttk.Combobox(top, textvariable=self.note_var, values=list(NOTE_FREQ_BASE.keys()), width=5).pack(side='left', padx=5)
self.octave_var = tk.IntVar(value=4)
ttk.Spinbox(top, from_=1, to=7, textvariable=self.octave_var, width=3).pack(side='left')
ttk.Label(top, text=l["octave"]).pack(side='left', padx=2)
self.duration_var = tk.IntVar(value=400)
ttk.Entry(top, textvariable=self.duration_var, width=5).pack(side='left', padx=5)
ttk.Label(top, text=l["time"]).pack(side='left')
ttk.Button(top, text=l["add"], command=self.add_note).pack(side='left', padx=10)
ttk.Button(top, text=l["del_note"], command=self.delete_selected_note).pack(side='left', padx=5)
self.tree = ttk.Treeview(self, columns=('N', 'D', 'I'), show='headings', selectmode='browse')
self.tree.heading('N', text=l['col_n']); self.tree.heading('D', text=l['col_d']); self.tree.heading('I', text=l['col_i'])
self.tree.pack(fill='both', expand=True, padx=10)
p_frame = tk.Frame(self, bg=bg_col); p_frame.pack(fill='x', padx=10, pady=5)
for n in ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B', 'P']:
ttk.Button(p_frame, text=n, width=3, command=lambda nt=n: self.add_note_from_piano(nt)).pack(side='left', padx=1)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().pack(fill='x', pady=5)
btns = tk.Frame(self, bg=bg_col); btns.pack(fill='x', padx=10, pady=10)
ttk.Button(btns, text=l["play"], command=self.play_polyphonic).pack(side='left', padx=5)
ttk.Button(btns, text=l["stop"], command=self.stop_playback_func).pack(side='left', padx=5)
ttk.Button(btns, text=l["clear"], command=self.clear_track).pack(side='left', padx=5)
self.update_track_label()
self.apply_theme()
def apply_theme(self):
style = ttk.Style()
style.theme_use('clam')
bg = "#2d2d2d" if self.current_theme == "dark" else "#f0f0f0"
fg = "#ffffff" if self.current_theme == "dark" else "#000000"
field = "#3d3d3d" if self.current_theme == "dark" else "#ffffff"
self.configure(bg=bg)
style.configure("TFrame", background=bg)
style.configure("TLabel", background=bg, foreground=fg)
style.configure("TButton", background="#444444" if self.current_theme == "dark" else "#e1e1e1", foreground=fg)
style.configure("Treeview", background=field, foreground=fg, fieldbackground=field)
style.configure("Treeview.Heading", background="#555555" if self.current_theme == "dark" else "#dddddd", foreground=fg)
style.configure("TSpinbox", fieldbackground=field, foreground=fg)
style.configure("TCombobox", fieldbackground=field, foreground=fg)
self.fig.patch.set_facecolor(bg)
self.ax_fft.set_facecolor('#1e1e1e' if self.current_theme=="dark" else "white")
self.ax_wave.set_facecolor('#1e1e1e' if self.current_theme=="dark" else "white")
self.canvas.draw_idle()
def show_info(self):
l = LANGS[self.current_lang]
bg = "#2d2d2d" if self.current_theme == "dark" else "#ffffff"
fg = "#ffffff" if self.current_theme == "dark" else "#000000"
info_win = tk.Toplevel(self)
info_win.title(l["info_title"])
info_win.geometry("400x250")
info_win.configure(bg=bg)
info_win.resizable(False, False)
info_win.transient(self)
info_win.grab_set()
tk.Label(info_win, text="PolyPy Engine", font=("Arial", 14, "bold"), bg=bg, fg="#00aaff").pack(pady=15)
tk.Label(info_win, text=l["info_msg"], wraplength=350, justify="center", bg=bg, fg=fg, font=("Arial", 10)).pack(padx=20, pady=10)
ttk.Button(info_win, text="OK", command=info_win.destroy).pack(pady=15)
def play_polyphonic(self):
if self.playing: return
self.playing = True
def loop():
audios = [self.get_track_audio(t) for t in self.tracks if t]
if not audios: self.playing = False; return
max_len = max(len(a) for a in audios)
combined = np.zeros(max_len, dtype=np.float32)
for a in audios: combined[:len(a)] += a * (1 / len(audios))
temp_f = "preview.wav"
with wave.open(temp_f, 'w') as f:
f.setnchannels(1); f.setsampwidth(2); f.setframerate(SAMPLERATE)
f.writeframes((combined * 32767).astype(np.int16).tobytes())
winsound.PlaySound(temp_f, winsound.SND_FILENAME | winsound.SND_ASYNC)
start_time = time.time()
chunk_size = 2048
while self.playing:
elapsed = time.time() - start_time
curr_sample = int(elapsed * SAMPLERATE)
if curr_sample + chunk_size > max_len: break
chunk = combined[curr_sample : curr_sample + chunk_size]
fft_data = np.abs(np.fft.rfft(chunk))[:60]
def update_plot(fd=fft_data, ch=chunk):
if not self.playing: return
self.ax_fft.clear(); self.ax_wave.clear()
c_eq = '#00ff00' if self.current_theme == "dark" else '#008800'
c_wv = '#00aaff' if self.current_theme == "dark" else '#0044aa'
self.ax_fft.bar(range(len(fd)), fd, color=c_eq, width=0.8)
self.ax_fft.set_ylim(0, max(0.5, np.max(fd)*1.2))
self.ax_fft.axis('off')
self.ax_wave.plot(ch[:500], color=c_wv)
self.ax_wave.set_ylim(-1.1, 1.1)
self.ax_wave.axis('off')
self.canvas.draw_idle()
self.after(0, update_plot)
time.sleep(0.04)
self.playing = False
threading.Thread(target=loop, daemon=True).start()
def generate_wave(self, freqs, duration_ms, vol, style):
samples = int((duration_ms / 1000) * SAMPLERATE)
if samples <= 0: return np.zeros(1)
t = np.linspace(0, duration_ms / 1000, samples, False)
combined_wave = np.zeros(samples)
active_freqs = [f for f in freqs if f > 0]
if not active_freqs: return np.zeros(samples)
for freq in active_freqs:
if style == "MIDI (Square)": w = np.sign(np.sin(2 * np.pi * freq * t))
elif style == "Pianino": w = np.sin(2 * np.pi * freq * t) * np.exp(-3 * t)
elif style == "Gitara": w = np.sin(2 * np.pi * freq * t) * np.exp(-1.5 * t)
elif style == "Gitara Przesterowana": w = np.clip(np.sin(2 * np.pi * freq * t) * 5, -1, 1)
elif style == "Perkusja (Noise)": w = np.random.uniform(-1, 1, samples) * np.exp(-12 * t)
else: w = np.sin(2 * np.pi * freq * t)
combined_wave += w
return (combined_wave / len(active_freqs)) * (vol / 100)
def get_track_audio(self, notes):
ratio = 120 / self.bpm.get()
full = np.array([], dtype=np.float32)
for n in notes:
full = np.concatenate([full, self.generate_wave(n.frequencies(), int(n.duration_ms * ratio), n.volume, n.instrument)])
return full
def setup_menu(self, l):
m = tk.Menu(self); f = tk.Menu(m, tearoff=0)
f.add_command(label=l["load"], command=self.load_melody)
f.add_command(label=l["save"], command=self.save_melody); f.add_separator()
f.add_command(label=l["import"], command=self.import_text)
f.add_command(label=l["export"], command=self.export_text); f.add_separator()
f.add_command(label=l["wav"], command=self.export_wav)
m.add_cascade(label=l["file"], menu=f)
e = tk.Menu(m, tearoff=0)
e.add_command(label=l["copy"], command=self.copy_track)
e.add_command(label=l["paste"], command=self.paste_track); e.add_separator()
e.add_command(label=l["oct_up"], command=lambda: self.shift_octave(1))
e.add_command(label=l["oct_down"], command=lambda: self.shift_octave(-1))
m.add_cascade(label=l["edit"], menu=e)
inst = tk.Menu(m, tearoff=0)
for s in ["Beep (classic)", "Pianino", "MIDI (Square)", "Gitara", "Gitara Przesterowana", "Keyboard (Sine)", "Perkusja (Noise)"]:
inst.add_radiobutton(label=s, variable=self.current_instrument, value=s)
m.add_cascade(label=l["instrument"], menu=inst)
m.add_command(label=l["settings"], command=self.open_settings)
# --- ZAKTUALIZOWANA OPCJA INFO ---
m.add_command(label=l["info_menu"], command=self.show_info)
self.config(menu=m)
def open_settings(self):
win = tk.Toplevel(self); lv = tk.StringVar(value=self.current_lang); tv = tk.StringVar(value=self.current_theme)
ttk.Label(win, text="Język/Lang").pack(pady=5); ttk.Combobox(win, textvariable=lv, values=["PL", "EN"]).pack()
ttk.Label(win, text="Motyw/Theme").pack(pady=5); ttk.Radiobutton(win, text="Dark", variable=tv, value="dark").pack(); ttk.Radiobutton(win, text="Light", variable=tv, value="light").pack()
ttk.Button(win, text="Zastosuj", command=lambda: [setattr(self, 'current_lang', lv.get()), setattr(self, 'current_theme', tv.get()), self.setup_ui(), win.destroy()]).pack(pady=10)
def update_track_label(self):
self.track_info_label.config(text=f"{LANGS[self.current_lang]['track']}: {self.current_track_index + 1} / {len(self.tracks)}")
self.refresh_notes_view()
def add_new_track(self): self.tracks.append([]); self.current_track_index = len(self.tracks)-1; self.update_track_label()
def remove_current_track(self):
if len(self.tracks) > 1: del self.tracks[self.current_track_index]; self.current_track_index = max(0, self.current_track_index-1); self.update_track_label()
def next_track(self):
if self.current_track_index < len(self.tracks)-1: self.current_track_index += 1; self.update_track_label()
def prev_track(self):
if self.current_track_index > 0: self.current_track_index -= 1; self.update_track_label()
def add_note(self): self.tracks[self.current_track_index].append(Note([self.note_var.get()], [self.octave_var.get()], self.duration_var.get(), 100, self.current_instrument.get())); self.refresh_notes_view()
def add_note_from_piano(self, name): self.tracks[self.current_track_index].append(Note([name], [self.octave_var.get() if name!='P' else 0], self.duration_var.get(), 100, self.current_instrument.get())); self.refresh_notes_view()
def delete_selected_note(self):
s = self.tree.selection()
if s: del self.tracks[self.current_track_index][self.tree.index(s[0])]; self.refresh_notes_view()
def refresh_notes_view(self):
self.tree.delete(*self.tree.get_children())
for n in self.tracks[self.current_track_index]:
self.tree.insert('', 'end', values=("+".join([f"{nm}{oc}" for nm, oc in zip(n.names, n.octaves)]), n.duration_ms, n.instrument))
def copy_track(self): self.clipboard = [n.to_dict() for n in self.tracks[self.current_track_index]]
def paste_track(self):
if self.clipboard:
self.tracks[self.current_track_index].extend([Note.from_dict(d) for d in self.clipboard])
self.refresh_notes_view()
def shift_octave(self, delta):
for n in self.tracks[self.current_track_index]:
n.octaves = [max(1, min(7, o + delta)) if o != 0 else 0 for o in n.octaves]
self.refresh_notes_view()
def load_melody(self):
p = filedialog.askopenfilename(filetypes=[("JSON Files", "*.json")])
if not p: return
with open(p, 'r') as f:
try:
data = json.load(f)
self.bpm.set(data.get('bpm', 120))
self.tracks = [[Note.from_dict(nd) for nd in t] for t in data.get('tracks', [[]])]
self.current_track_index = 0
self.update_track_label()
except: messagebox.showerror("Błąd", "Niepoprawny format pliku")
def save_melody(self):
p = filedialog.asksaveasfilename(defaultextension=".json")
if p:
with open(p, 'w') as f: json.dump({'bpm': self.bpm.get(), 'tracks': [[n.to_dict() for n in t] for t in self.tracks]}, f, indent=4)
def export_wav(self):
path = filedialog.asksaveasfilename(defaultextension=".wav", filetypes=[("WAV Audio", "*.wav")])
if not path: return
audios = [self.get_track_audio(t) for t in self.tracks if t]
max_len = max(len(a) for a in audios); combined = np.zeros(max_len, dtype=np.float32)
for a in audios: combined[:len(a)] += a * (1 / len(audios))
with wave.open(path, 'w') as f:
f.setnchannels(1); f.setsampwidth(2); f.setframerate(SAMPLERATE)
f.writeframes((combined * 32767).astype(np.int16).tobytes())
messagebox.showinfo("OK", "WAV zapisany")
def import_text(self):
t = simpledialog.askstring("Import", "Format: C4+E4 400 100")
if t:
try:
for line in t.strip().split('\n'):
p = line.split(); ch = p[0].upper().split('+'); nms, ocs = [], []
for itm in ch:
if itm.startswith('P'): nms.append('P'); ocs.append(0)
else: n = itm[:2] if '#' in itm else itm[0]; ocs.append(int("".join(filter(str.isdigit, itm)) or 4)); nms.append(n)
self.tracks[self.current_track_index].append(Note(nms, ocs, int(p[1]), int(p[2]), " ".join(p[3:]) or self.current_instrument.get()))
self.refresh_notes_view()
except: messagebox.showerror("Error", "Błąd formatu")
def export_text(self):
out = "\n".join(["+".join([f"{nm}{oc}" for nm, oc in zip(n.names, n.octaves)]) + f" {n.duration_ms} {n.volume} {n.instrument}" for n in self.tracks[self.current_track_index]])
top = tk.Toplevel(self); txt = tk.Text(top); txt.insert('1.0', out); txt.pack(); ttk.Button(top, text="OK", command=top.destroy).pack()
def stop_playback_func(self): winsound.PlaySound(None, winsound.SND_PURGE); self.playing = False
def clear_track(self): self.tracks[self.current_track_index] = []; self.refresh_notes_view()
if __name__ == "__main__":
app = PolyPy()
app.mainloop()