-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMidiInfo_support.py
441 lines (382 loc) · 12.8 KB
/
MidiInfo_support.py
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 7.6
# in conjunction with Tcl version 8.6
# Feb 09, 2023 11:26:49 AM CST platform: Linux
# Feb 09, 2023 12:28:51 PM CST platform: Linux
# ======================================================
# MidiInfo_support.py
# ------------------------------------------------------
# Created for Full Circle Magazine Issue #191
# Written by G.D. Walters
# Copyright (c) 2023 by G.D. Walters
# This source code is released under the MIT License
# ======================================================
import sys
import os
import platform
import subprocess
import shared
import mido
from mido import MidiFile, Message, tempo2bpm
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
from tkinter import filedialog as filedialog
from tkinter import messagebox as messagebox
import MidiInfo
_debug = True # False to eliminate debug printing from callback functions.
location = MidiInfo._location
version = "0.1.2"
def main(*args):
"""Main entry point for the application."""
global root
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", root.destroy)
# Creates a toplevel widget.
global _top1, _w1
_top1 = root
_w1 = MidiInfo.Toplevel1(_top1)
startup()
root.mainloop()
def startup():
global sty
sty = ttk.Style()
# Cursor stuff
global busyCursor, preBusyCursors, busyWidgets
busyCursor = "watch"
preBusyCursors = None
busyWidgets = (root,)
show_program_info()
load_tcl_themes()
sty.theme_use("notsodark")
fix_ttkLabels()
set_icon()
setup_vars()
set_titlebar()
# ports()
clear_display()
shared.lastpath = location
centre_screen(718, 438)
def set_titlebar():
shared.basetitle = f"Midi Info version {version}"
_top1.title(shared.basetitle)
def clear_display():
_w1.KeySignature.set("")
_w1.Songlength.set("")
_w1.TimeSignature.set("")
_w1.Tempo.set("")
_w1.MidiFileType.set("")
def load_tcl_themes():
# ===================================================
# This will load the various tcl Themes.
# ===================================================
# Load my NotSoDark theme
global sty
_top1.tk.call("source", os.path.join(location, "themes", "notsodark.tcl"))
def fix_ttkLabels():
global sty
labellist = [
_w1.TLabel1,
_w1.TLabel2,
_w1.TLabel3,
_w1.TLabel4,
_w1.TLabel5,
_w1.TLabel6,
_w1.TLabel7,
_w1.TLabel8,
_w1.TLabel9,
_w1.TLabel10,
_w1.TLabel11,
]
_bgcolor = sty.lookup(".", "background")
_fgcolor = sty.lookup(".", "foreground")
for lab in labellist:
lab.config(background=_bgcolor)
lab.config(foreground=_fgcolor)
def on_btnAbout(*args):
if _debug:
print("MidiInfo_support.on_btnAbout")
for arg in args:
print(" another arg:", arg)
sys.stdout.flush()
titl = "Midi Info"
msg = "Sorry, About is not finished yet"
messagebox.showinfo(titl, msg, parent=_top1, icon=messagebox.INFO)
def on_btnExit(*args):
if _debug:
print("MidiInfo_support.on_btnExit")
for arg in args:
print(" another arg:", arg)
sys.stdout.flush()
sys.exit()
def on_btnOpen(*args):
global filename
global busyCursor, preBusyCursors, busyWidgets
if _debug:
print("MidiInfo_support.on_btnOpen")
for arg in args:
print(" another arg:", arg)
sys.stdout.flush()
filename = filedialog.askopenfilename(
initialdir=shared.lastpath,
title="Select A MIDI File",
filetypes=(("midi files", "*.mid"), ("ALL Files", "*.*")),
)
print(filename)
if filename != ():
# if _debug:
# print(filename)
# Get the filename of the midi file
shared.midifilename = os.path.basename(filename)
shared.lastpath = os.path.dirname(filename)
print(shared.midifilename)
# Add it to the titlebar app title
_top1.title(f"{shared.basetitle} - {shared.midifilename}")
mid = MidiFile(filename)
busyStart()
clear_display()
parse_midi_file(mid)
if _debug:
print(f"{shared.tempo=}")
_w1.KeySignature.set(shared.key_signature)
_w1.TimeSignature.set(shared.time_signature)
_w1.Tempo.set(shared.tempo)
_w1.MidiFileType.set(shared.miditype)
songlength = mid.length
slen = f"{int(songlength/60)} minutes, {int(songlength%60)} seconds."
_w1.Songlength.set(slen)
if _debug:
print(f"{shared.time_signature=}")
print(f"{shared.key_signature=}")
print(f"{shared.tracks}")
# delete_list_items()
FillListBox()
busyEnd()
def FillListBox():
for itm in shared.tracks:
dat = f"{itm[0]} - {itm[1]}"
_w1.Scrolledlistbox1.insert("end", dat)
_w1.Scrolledlistbox1.bind("<<ListboxSelect>>", on_listboxSelect)
def on_listboxSelect(e):
indx = _w1.Scrolledlistbox1.curselection()
itm = _w1.Scrolledlistbox1.get(indx[0])
# SelectedItem.set(f"Selected Item: {indx[0]} - {itm}")
print(f"Selected Item: {indx[0]} - {itm}")
def delete_list_items():
if _debug:
print("DeleteListItems")
sys.stdout.flush()
_w1.Scrolledlistbox1.delete(0, END)
def setup_vars():
shared.lastpath = ""
shared.midifilename = ""
shared.miditype = ""
shared.trackname = ""
shared.tracknumber = ""
shared.tracks = []
shared.tracktext = ""
shared.copyright = ""
shared.instrument_name = ""
shared.lyrics = ""
shared.marker = ""
shared.cue_marker = ""
shared.device_name = ""
shared.channel_prefix = ""
shared.tempo = ""
shared.midi_port = ""
shared.time_signature = ""
shared.key_signature = ""
shared.sequencer_specific = ""
def parse_midi_file(filedata):
global busyCursor, preBusyCursors, busyWidgets
delete_list_items()
cntr = 0
shared.tracks = []
shared.miditype = filedata.type
for i, track in enumerate(filedata.tracks):
for msg in track:
if msg.is_meta:
mesg = str(msg)
mesg = mesg[11:]
if "track_name" in mesg:
pos = mesg.find("name=") + 6
pos2 = mesg.find("'", pos + 1)
# print(f"{pos},{pos2}")
tn = mesg[pos:pos2]
if _debug:
print(f"Track: {i} Name: {tn}")
trackinfo = [i, tn]
shared.tracks.append(trackinfo)
elif "end_of_track" in mesg:
pass
# print(f"Track: {i} ENDOFTRACK")
elif "number" in mesg:
if _debug:
print(f"Track: {i} number")
elif "text" in mesg:
pass
# if _debug:
# print(f"Track: {i} text")
elif "copyright" in mesg:
if _debug:
print(f"Track: {i} copyright")
elif "instrument_name" in mesg:
if _debug:
print(f"Track: {i} instrument")
elif "lyrics" in mesg:
if _debug:
print(f"Track: {i} lyrics")
elif "marker" in mesg:
if _debug:
print(f"Track: {i} marker")
elif "cue_marker" in mesg:
if _debug:
print(f"Track: {i} cue marker")
elif "device_name" in mesg:
if _debug:
print(f"Track: {i} device")
elif "channel_prefix" in mesg:
if _debug:
print(f"Track: {i} channel prefix")
elif "midi_port" in mesg:
if _debug:
print(f"Track: {i} midi port")
elif "set_tempo" in mesg:
# Tempo is in microseconds per beat (quarter note). You can use
# :py:func:`bpm2tempo` and :py:func:`tempo2bpm` to convert to and from
# beats per minute. Note that :py:func:`tempo2bpm` may return a floating
# point number.
pos1 = mesg.find("tempo=") + 6
pos2 = mesg.find(",", pos1)
tempo = mesg[pos1:pos2]
timesig = (4, 4)
# print(f"tempo={tempo} - timesig={timesig}")
bpm = int(mido.midifiles.tempo2bpm(int(tempo)))
if _debug:
print(f"Track: {i} - tempo: {bpm}")
shared.tempo = bpm
elif "smpte_offset" in mesg:
pass
# print(f"Track: {i} smpte offset")
elif "time_signature" in mesg:
pos1 = mesg.find("numerator=") + 10
pos2 = mesg.find(",", pos1)
pos3 = mesg.find("denominator=") + 12
pos4 = mesg.find(",", pos3)
# print(f"{pos1}-{pos2} = {pos3}-{pos4}")
num = mesg[pos1:pos2]
denom = mesg[pos3:pos4]
tsig = f"{num}/{denom}"
if _debug:
print(f"Track: {i} - Time Sig: {tsig}")
shared.time_signature = tsig
elif "key_signature" in mesg:
pos1 = mesg.find("key='") + 5
pos2 = mesg.find("'", pos1)
# print(f"{pos1}-{pos2}")
keysig = mesg[pos1:pos2]
if _debug:
print(f"Track: {i} key_sig: {keysig}")
shared.key_signature = keysig
elif "sequencer_specific" in mesg:
if _debug:
print("")
# print(f"Track: {i} seq specific")
else:
if _debug:
print(f"Track: {i} unknown message")
def print_ports(heading, port_names):
print(heading)
for name in port_names:
print(f" '{name}'")
print()
def ports():
print()
print_ports("Available input Ports:", mido.get_input_names())
print_ports("Available output Ports:", mido.get_output_names())
for name in [
"MIDO_DEFAULT_INPUT",
"MIDO_DEFAULT_OUTPUT",
"MIDO_DEFAULT_IOPORT",
"MIDO_BACKEND",
]:
try:
value = os.environ[name]
print(f"{name}={value!r}")
except LookupError:
print(f"{name} not set.")
print()
print(f"Using backend {mido.backend.name}.")
print()
def play_midi(filename):
sound_font = "/usr/share/sounds/sf2/FluidR3_GM.sf2"
subprocess.call(
[
"fluidsynth",
"-a",
"alsa",
"-m",
"alsa_seq",
"-i",
"-g",
"0.2",
sound_font,
filename,
"-r",
"44100",
]
)
def on_btnPlay(*args):
global filename
if _debug:
print("MidiInfo_support.on_btnPlay")
for arg in args:
print(" another arg:", arg)
sys.stdout.flush()
play_midi(filename)
def centre_screen(wid, hei):
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws / 2) - (wid / 2)
y = (hs / 2) - (hei / 2)
root.geometry("%dx%d+%d+%d" % (wid, hei, x, y))
def set_icon():
# ======================================================
# Sets the application icon...
# ======================================================
global progImagesPath
img = os.path.join(location, "graphics", "midifile.png")
shared.p1 = tk.PhotoImage(file=img)
root.tk.call("wm", "iconphoto", root._w, shared.p1)
def show_program_info():
global version
pv = platform.python_version()
print(f"Running under Python {pv}")
print(location)
print(f"Version: {version}")
def busyStart(newcursor=None):
global preBusyCursors
if not newcursor:
newcursor = busyCursor
newPreBusyCursors = {}
for component in busyWidgets:
newPreBusyCursors[component] = component["cursor"]
component.configure(cursor=newcursor)
component.update_idletasks()
preBusyCursors = (newPreBusyCursors, preBusyCursors)
def busyEnd():
global preBusyCursors
if not preBusyCursors:
return
oldPreBusyCursors = preBusyCursors[0]
preBusyCursors = preBusyCursors[1]
for component in busyWidgets:
try:
component.configure(cursor=oldPreBusyCursors[component])
except KeyError:
pass
component.update_idletasks()
if __name__ == "__main__":
MidiInfo.start_up()