-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrolMenu.py
1173 lines (976 loc) · 59.4 KB
/
controlMenu.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
import math
import librosa, librosa.display
import parselmouth
import numpy as np
import sounddevice as sd
import matplotlib as mpl
import matplotlib.pyplot as plt
from tkinter import ttk
from scipy import signal
from matplotlib.widgets import Button, Cursor, SpanSelector, MultiCursor
from matplotlib.backend_bases import MouseButton, MouseEvent
from matplotlib.patches import Rectangle
from scipy.io.wavfile import write
from auxiliar import Auxiliar
from pitchAdvancedSettings import AdvancedSettings
# To avoid blurry fonts
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
class ControlMenu():
def createControlMenu(self, root, fileName, fs, audioFrag):
self.fileName = fileName
self.audio = audioFrag # audio array of the fragment
self.fs = fs # sample frequency of the audio (Hz)
self.time = np.arange(0, len(self.audio)/self.fs, 1/self.fs) # time array of the audio
self.duration = max(self.time) # duration of the audio (s)
self.lenAudio = len(self.audio) # length of the audio array
self.aux = Auxiliar()
self.adse = AdvancedSettings()
cm = tk.Toplevel()
self.plotFT(cm) # show the figure of the FT
cm.resizable(True, True)
cm.title(self.fileName)
cm.iconbitmap('icons/icon.ico')
cm.wm_transient(root) # Place the toplevel window at the top
# self.aux.windowGeometry(cm, 750, 575)
# Adapt the window to different sizes
for i in range(3):
cm.columnconfigure(i, weight=1)
for i in range(14):
cm.rowconfigure(i, weight=1)
# If the 'Control menu' window is closed, close also all the generated figures
def on_closing():
cm.destroy()
plt.close('all') # closes all matplotlib figures
cm.protocol("WM_DELETE_WINDOW", on_closing)
# LABELS
# Labels of OptionMenus
lab_opts = tk.Label(cm, text='Choose an option', bd=6, font=('TkDefaultFont', 10, 'bold'))
lab_wind = tk.Label(cm, text='Window')
lab_nfft = tk.Label(cm, text='nfft')
lab_meth = tk.Label(cm, text='Method')
lab_type = tk.Label(cm, text='Filter type')
# Labels of Entrys
lab_size = tk.Label(cm, text='Window length (s)')
lab_over = tk.Label(cm, text='Overlap (s)')
lab_minf = tk.Label(cm, text='Min frequency (Hz)')
lab_maxf = tk.Label(cm, text='Max frequency (Hz)')
lab_minp = tk.Label(cm, text='Pitch floor (Hz)')
lab_maxp = tk.Label(cm, text='Pitch ceiling (Hz)')
lab_fund = tk.Label(cm, text='Fund. freq. multiplication')
lab_cent = tk.Label(cm, text='Center frequency')
lab_cut1 = tk.Label(cm, text='Fcut1')
lab_cut2 = tk.Label(cm, text='Fcut2')
lab_beta = tk.Label(cm, text='Beta')
lab_fshz = tk.Label(cm, text='Fs: '+str(self.fs)+' Hz')
lab_spec = tk.Label(cm, text='Spectrogram', bd=6, font=('TkDefaultFont', 10))
lab_ptch = tk.Label(cm, text='Pitch', bd=6, font=('TkDefaultFont', 10))
lab_filt = tk.Label(cm, text='Filtering', bd=6, font=('TkDefaultFont', 10))
lab_sten = tk.Label(cm, text='Short-Time-Energy', bd=6, font=('TkDefaultFont', 10))
# Labels of Radiobuttons
lab_draw = tk.Label(cm, text='Drawing style')
# positioning Labels
lab_opts.grid(column=0, row=0, sticky=tk.E, columnspan=2)
lab_wind.grid(column=0, row=1, sticky=tk.E)
lab_nfft.grid(column=0, row=3, sticky=tk.E)
lab_meth.grid(column=0, row=10, sticky=tk.E)
lab_type.grid(column=2, row=2, sticky=tk.E)
lab_size.grid(column=0, row=2, sticky=tk.E)
lab_over.grid(column=0, row=4, sticky=tk.E)
lab_minf.grid(column=0, row=6, sticky=tk.E)
lab_maxf.grid(column=0, row=7, sticky=tk.E)
lab_draw.grid(column=0, row=8, sticky=tk.E)
lab_minp.grid(column=0, row=11, sticky=tk.E)
lab_maxp.grid(column=0, row=12, sticky=tk.E)
lab_fund.grid(column=2, row=3, sticky=tk.E)
lab_cent.grid(column=2, row=4, sticky=tk.E)
lab_cut1.grid(column=2, row=5, sticky=tk.E)
lab_cut2.grid(column=2, row=6, sticky=tk.E)
lab_beta.grid(column=2, row=11, sticky=tk.E)
lab_fshz.grid(column=3, row=13, sticky=tk.EW)
lab_spec.grid(column=1, row=5)
lab_ptch.grid(column=1, row=9)
lab_filt.grid(column=3, row=1)
lab_sten.grid(column=3, row=10)
# ENTRYS
cm.var_size = tk.DoubleVar(value=0.03)
cm.var_over = tk.DoubleVar(value=0.01)
cm.var_minf = tk.IntVar()
cm.var_maxf = tk.IntVar(value=self.fs/2)
cm.var_minp = tk.DoubleVar(value=75.0)
cm.var_maxp = tk.DoubleVar(value=600.0)
cm.var_fund = tk.IntVar(value=1)
cm.var_cent = tk.IntVar(value=400)
cm.var_cut1 = tk.IntVar(value=200)
cm.var_cut2 = tk.IntVar(value=600)
cm.var_beta = tk.IntVar()
vcmd = (cm.register(self.aux.onValidate), '%S', '%s', '%d')
ent_size = ttk.Entry(cm, textvariable=cm.var_size, state='disabled', validate='key', validatecommand=vcmd)
ent_over = ttk.Entry(cm, textvariable=cm.var_over, state='disabled', validate='key', validatecommand=vcmd)
ent_minf = ttk.Entry(cm, textvariable=cm.var_minf, state='disabled', validate='key', validatecommand=vcmd)
ent_maxf = ttk.Entry(cm, textvariable=cm.var_maxf, state='disabled', validate='key', validatecommand=vcmd)
ent_minp = ttk.Entry(cm, textvariable=cm.var_minp, state='disabled', validate='key', validatecommand=vcmd)
ent_maxp = ttk.Entry(cm, textvariable=cm.var_maxp, state='disabled', validate='key', validatecommand=vcmd)
ent_fund = ttk.Entry(cm, textvariable=cm.var_fund, state='disabled', validate='key', validatecommand=vcmd)
ent_cent = ttk.Entry(cm, textvariable=cm.var_cent, state='disabled', validate='key', validatecommand=vcmd)
ent_cut1 = ttk.Entry(cm, textvariable=cm.var_cut1, state='disabled', validate='key', validatecommand=vcmd)
ent_cut2 = ttk.Entry(cm, textvariable=cm.var_cut2, state='disabled', validate='key', validatecommand=vcmd)
ent_beta = ttk.Entry(cm, textvariable=cm.var_beta, state='disabled', validate='key', validatecommand=vcmd)
# Called when inserting a value in the entry of the window length and pressing enter
def windowLengthEntry(event):
# Show an error and stop if the inserted window size is incorrect
windSize = cm.var_size.get()
overlap = cm.var_over.get()
if windSize > self.duration or windSize == 0:
# Reset widgets
cm.var_size.set(0.03)
cm.opt_nfft = [2**9, 2**10, 2**11, 2**12, 2**13, 2**14, 2**15, 2**16, 2**17, 2**18, 2**19]
self.updateOptionMenu(cm, dd_nfft)
if windSize > self.duration: # The window size can't be greater than the duration of the signal
text = "The window size can't be greater than the duration of the signal (" + str(round(self.duration, 2)) + "s)."
tk.messagebox.showerror(parent=cm, title="Window size too long", message=text) # show error
elif windSize == 0: # The window size must be a positive number
tk.messagebox.showerror(parent=cm, title="Wrong window size value", message="The chosen value for the window size must be a positive number.") # show error
elif windSize < overlap: # The window size must always be greater than the overlap
cm.var_size.set(overlap+0.01)
text2 = "The window size must always be greater than the overlap (" + str(overlap) + "s)."
tk.messagebox.showerror(parent=cm, title="Wrong overlap value", message=text2) # show error
# Change the values of nfft to be always greater than the window size
else:
windSizeSamp = windSize * self.fs # window size in samples
nfft = cm.opt_nfft[0] # the smallest value of the nfft list
if nfft < windSizeSamp: # Deletes smallest values of the nfft list and adds greater ones
last = int(math.log2(cm.opt_nfft[len(cm.opt_nfft)-1])) + 1
first = int(math.log2(nfft))
while 2**first < windSizeSamp:
for a in range(len(cm.opt_nfft)-1):
cm.opt_nfft[a] = cm.opt_nfft[a+1]
cm.opt_nfft[len(cm.opt_nfft)-1] = 2**last
last += 1
first += 1
self.updateOptionMenu(cm, dd_nfft)
else: # Adds smaller values to the nfft list if possible
first = int(math.log2(nfft)) - 1
while 2**first > windSizeSamp:
for a in range(len(cm.opt_nfft)-1, 0, -1):
cm.opt_nfft[a] = cm.opt_nfft[a-1]
cm.opt_nfft[0] = 2**first
self.updateOptionMenu(cm, dd_nfft)
first -= 1
return True
def overlapEntry(event):
# Show an error and stop if the inserted overlap is incorrect
overlap = cm.var_over.get()
windSize = cm.var_size.get()
if overlap > self.duration or overlap >= windSize:
cm.var_over.set('0.01') # Reset widget
if overlap > self.duration: # The overlap can't be greater than the duration of the signal
text = "The overlap can't be greater than the duration of the signal (" + str(round(self.duration, 2)) + "s)."
tk.messagebox.showerror(parent=cm, title="Overlap too long", message=text) # show error
elif overlap >= windSize: # The overlap must always be smaller than the window size
text2 = "The overlap must always be smaller than the window size (" + str(windSize) + "s)."
tk.messagebox.showerror(parent=cm, title="Wrong overlap value", message=text2) # show error
else: return True
def minfreqEntry(event):
# The minimum frequency must be >= 0 and smaller than the maximum frequency
minfreq = cm.var_minf.get()
maxfreq = cm.var_maxf.get()
if minfreq >= maxfreq:
cm.var_minf.set('0') # Reset widget
text = "The minimum frequency must be smaller than the maximum frequency (" + str(maxfreq) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Minimum frequency too big", message=text) # show error
else: return True
def maxfreqEntry(event):
# The maximum frequency must be <= self.fs/2 and greater than the minimum frequency
minfreq = cm.var_minf.get()
maxfreq = cm.var_maxf.get()
if maxfreq > self.fs/2 or maxfreq <= minfreq:
cm.var_maxf.set(self.fs/2) # Reset widget
if maxfreq > self.fs/2:
text = "The maximum frequency can't be greater than the half of the sample frequency (" + str(self.fs/2) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Maximum frequency too big", message=text) # show error
elif maxfreq <= minfreq:
text = "The maximum frequency must be greater than the minimum frequency (" + str(minfreq) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Maximum frequency too small", message=text) # show error
else: return True
def minpitchEntry(event):
minPitch = cm.var_minp.get()
maxPitch = cm.var_maxp.get()
if minPitch >= maxPitch:
cm.var_minp.set('75.0') # Reset widget
cm.var_maxp.set('600.0') # Reset widget
text = "The minimum pitch must be smaller than the maximum pitch (" + str(maxPitch) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Pitch floor too big", message=text) # show error
else: return True
def maxpitchEntry(event):
minPitch = cm.var_minp.get()
maxPitch = cm.var_maxp.get()
if maxPitch <= minPitch:
cm.var_minp.set('75.0') # Reset widget
cm.var_maxp.set('600.0') # Reset widget
text = "The maximum pitch must be greater than the minimum pitch (" + str(minPitch) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Pitch ceiling too small", message=text) # show error
else: return True
def fundfreqEntry(event):
fundfreq = cm.var_fund.get()
if fundfreq < 1:
cm.var_fund.set('1')
text = "The minimum value of the fundamental frequency response is 1."
tk.messagebox.showerror(parent=cm, title="Fundamental frequency response too small", message=text) # show error
elif fundfreq > (self.fs/2): # max fundfreq = (self.fs/2)-(max(anchura de banda)/2) (?)
cm.var_fund.set(self.fs/2)
text = "The maximum frequency can't be greater than the half of the sample frequency (" + str(self.fs/2) + "Hz)."
tk.messagebox.showerror(parent=cm, title="Fundamental frequency response too big", message=text) # show error
else: return True
def centerEntry(event):
center = cm.var_cent.get()
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
if center <= fcut1 or center >= fcut2:
cm.var_cent.set(int((fcut1+fcut2)/2))
text = "The center frequency must be a value between fcut1 (" + str(fcut1) + ") and fcut2 (" + str(fcut2) + ")."
tk.messagebox.showerror(parent=cm, title="Wrong center frequency value", message=text) # show error
else: return True
def fcut1Entry(event):
center = cm.var_cent.get()
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
if fcut1 >= fcut2 or fcut1 >= center:
c1 = fcut2-center
c1 = center-c1
cm.var_cut1.set(c1)
text = "Fcut1 must be a smaller value than center (" + str(center) + ") and fcut2 (" + str(fcut2) + ")."
tk.messagebox.showerror(parent=cm, title="Wrong fcut1 value", message=text) # show error
else: return True
def fcut2Entry(event):
center = cm.var_cent.get()
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
if fcut2 <= fcut1 or fcut2 <= center:
c2 = center-fcut1
c2 = center+c2
cm.var_cut1.set(c2)
text = "Fcut2 must be a greater value than center (" + str(center) + ") and fcut1 (" + str(fcut1) + ")."
tk.messagebox.showerror(parent=cm, title="Wrong fcut2 value", message=text) # show error
else: return True
def betaEntry(event):
beta = cm.var_beta.get()
if beta < 0 or beta > 14:
cm.var_beta.set('0') # Reset widget
text = "The value of beta must be a number between 0 and 14."
tk.messagebox.showerror(parent=cm, title="Incorrect value of beta", message=text) # show error
else: return True
# calling functions after entering a value and pressing enter
ent_size.bind('<Return>', windowLengthEntry)
ent_over.bind('<Return>', overlapEntry)
ent_minf.bind('<Return>', minfreqEntry)
ent_maxf.bind('<Return>', maxfreqEntry)
ent_minp.bind('<Return>', minpitchEntry)
ent_maxp.bind('<Return>', maxpitchEntry)
ent_fund.bind('<Return>', fundfreqEntry)
ent_cent.bind('<Return>', centerEntry)
ent_cut1.bind('<Return>', fcut1Entry)
ent_cut2.bind('<Return>', fcut2Entry)
ent_beta.bind('<Return>', betaEntry)
# positioning Entrys
ent_size.grid(column=1, row=2, sticky=tk.EW, padx=5, pady=5, columnspan=1)
ent_over.grid(column=1, row=4, sticky=tk.EW, padx=5, pady=5, columnspan=1)
ent_minf.grid(column=1, row=6, sticky=tk.EW, padx=5, pady=5)
ent_maxf.grid(column=1, row=7, sticky=tk.EW, padx=5, pady=5)
ent_minp.grid(column=1, row=11, sticky=tk.EW, padx=5, pady=5)
ent_maxp.grid(column=1, row=12, sticky=tk.EW, padx=5, pady=5)
ent_fund.grid(column=3, row=3, sticky=tk.EW, padx=5, pady=5)
ent_cent.grid(column=3, row=4, sticky=tk.EW, padx=5, pady=5)
ent_cut1.grid(column=3, row=5, sticky=tk.EW, padx=5, pady=5)
ent_cut2.grid(column=3, row=6, sticky=tk.EW, padx=5, pady=5)
ent_beta.grid(column=3, row=11, sticky=tk.EW, padx=5, pady=5)
# RADIOBUTTONS
cm.var_draw = tk.IntVar(value=1)
rdb_lin = tk.Radiobutton(cm, text='linear', variable=cm.var_draw, value=1, state='disabled')
rdb_mel = tk.Radiobutton(cm, text='mel', variable=cm.var_draw, value=2, state='disabled')
rdb_lin.grid(column=1, row=8, sticky=tk.W)
rdb_mel.grid(column=1, row=8, sticky=tk.NS)
# CHECKBOX
cm.var_spec = tk.IntVar(value=0)
chk_spec = ttk.Checkbutton(cm, text='Show spectrogram', variable=cm.var_spec, state='disabled')
chk_spec.grid(column=1, row=13, sticky=tk.W)
# BUTTONS
# Checks if all the values inserted by the user are correct
def checkValues():
choice = cm.var_opts.get()
windSize = cm.var_size.get() # window size in seconds
overlap = cm.var_over.get() # overlap in seconds
minfreq = cm.var_minf.get()
maxfreq = cm.var_maxf.get()
beta = cm.var_beta.get()
minpitch = cm.var_minp.get()
maxpitch = cm.var_maxp.get()
fundfreq = cm.var_fund.get()
center = cm.var_cent.get()
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
if choice == 'STFT' or choice == 'STFT + Spect' or choice == 'Spectral Centroid' or choice == 'Spectrogram' or choice == 'Filtering' or choice == 'Short-Time-Energy':
if choice == 'Short-Time-Energy' and betaEntry(beta)!=True:
return
if minfreqEntry(minfreq)!=True or maxfreqEntry(maxfreq)!=True:
return
if choice == 'Filtering' and (fundfreqEntry(fundfreq)!=True or centerEntry(center)!=True or fcut1Entry(fcut1)!=True or fcut2Entry(fcut2)!=True):
return
if choice != 'Filtering' and windowLengthEntry(windSize) != True:
return
if (choice == 'STFT + Spect' or choice == 'Spectral Centroid' or choice == 'Short-Time-Energy' or choice == 'Spectrogram') and overlapEntry(overlap) != True:
return
elif choice == 'Pitch' and (minpitchEntry(minpitch) != True or maxpitchEntry(maxpitch) != True):
return
self.plotFigure(cm, choice, windSize, overlap, minfreq, maxfreq, beta)
but_adse = ttk.Button(cm, state='disabled', command=lambda: self.adse.advancedSettings(), text='Advanced settings')
but_freq = ttk.Button(cm, state='disabled', command=lambda: self.plotFiltFreqResponse(cm), text='Filter Frequency Response')
but_rese = ttk.Button(cm, state='disabled', text='Reset Signal')
# but_fisi = ttk.Button(cm, state='disabled', text='Filter Signal')
but_plot = ttk.Button(cm, command=lambda: checkValues(), text='Plot')
but_help = ttk.Button(cm, command=lambda: self.controller.help.createHelpMenu(cm, 8), text='🛈', width=2)
# positioning Buttons
but_adse.grid(column=1, row=14, sticky=tk.EW, padx=5, pady=5)
but_freq.grid(column=3, row=8, sticky=tk.EW, padx=5, pady=5)
but_rese.grid(column=3, row=9, sticky=tk.EW, padx=5, pady=5)
# but_fisi.grid(column=3, row=9, sticky=tk.EW, padx=5, pady=5)
but_plot.grid(column=3, row=14, sticky=tk.EW, padx=5, pady=5)
but_help.grid(column=2, row=14, sticky=tk.E, padx=5, pady=5)
# OPTION MENUS
cm.options = ('FT','STFT', 'Spectrogram','STFT + Spect', 'Short-Time-Energy', 'Pitch', 'Spectral Centroid', 'Filtering')
cm.opt_wind = ('Bartlett','Blackman', 'Hamming','Hanning', 'Kaiser')
cm.opt_nfft = [2**9, 2**10, 2**11, 2**12, 2**13, 2**14, 2**15, 2**16, 2**17, 2**18, 2**19]
cm.opt_meth = ('Autocorrelation', 'Cross-correlation', 'Subharmonics', 'Spinet')
cm.opt_pass = ('Lowpass','Highpass', 'Bandpass', 'Bandstop')
cm.opt_filt = ('Butterworth','Elliptic', 'Chebyshev I', 'Chebyshev II', 'FIR least-squares')
cm.var_opts = tk.StringVar()
cm.var_wind = tk.StringVar()
cm.var_nfft = tk.IntVar()
cm.var_meth = tk.StringVar()
cm.var_filt = tk.StringVar()
cm.var_pass = tk.StringVar()
# Called when changing the main option (FT, STFT, etc.) for disabling or activating widgets
def displayOptions(choice):
if choice == 'FT' or choice == 'STFT' or choice == 'Pitch' or choice == 'Filtering':
ent_over.config(state='disabled')
else: ent_over.config(state='normal')
if choice == 'FT' or choice == 'Pitch' or choice == 'Filtering':
ent_size.config(state='disabled')
else: ent_size.config(state='normal')
if choice == 'Filtering':
ent_fund.config(state='normal')
ent_cent.config(state='normal')
ent_cut1.config(state='normal')
ent_cut2.config(state='normal')
dd_filt.config(state='active')
dd_pass.config(state='active')
but_freq.configure(state='active')
but_rese.configure(state='active')
# but_fisi.configure(state='active')
else:
ent_fund.config(state='disabled')
ent_cent.config(state='disabled')
ent_cut1.config(state='disabled')
ent_cut2.config(state='disabled')
dd_filt.config(state='disabled')
dd_pass.config(state='disabled')
but_freq.configure(state='disabled')
but_rese.configure(state='disabled')
# but_fisi.configure(state='disabled')
if choice == 'Pitch':
self.adse.createVariables() # create the variables of advanced settings
dd_meth.config(state='active')
ent_minp.config(state='normal')
ent_maxp.config(state='normal')
chk_spec.config(state='active')
but_adse.config(state='active')
else:
dd_meth.config(state='disabled')
ent_minp.config(state='disabled')
ent_maxp.config(state='disabled')
chk_spec.config(state='disabled')
but_adse.config(state='disabled')
if choice == 'Spectrogram' or choice == 'STFT + Spect' or choice == 'Spectral Centroid' or choice == 'Filtering':
rdb_lin.config(state='active')
rdb_mel.config(state='active')
else:
rdb_lin.config(state='disabled')
rdb_mel.config(state='disabled')
if choice == 'Spectrogram' or choice == 'STFT + Spect' or choice == 'Spectral Centroid':
ent_minf.config(state='normal')
ent_maxf.config(state='normal')
else:
ent_minf.config(state='disabled')
ent_maxf.config(state='disabled')
if choice == 'STFT' or choice == 'Spectrogram' or choice == 'STFT + Spect' or choice == 'Spectral Centroid' or choice == 'Short-Time-Energy':
dd_wind.config(state='active')
else: dd_wind.config(state='disabled')
if choice == 'STFT' or choice == 'Spectrogram' or choice == 'STFT + Spect' or choice == 'Spectral Centroid':
dd_nfft.config(state='active')
else: dd_nfft.config(state='disabled')
if choice == 'Short-Time-Energy':
ent_beta.config(state='normal')
else: ent_beta.config(state='disabled')
# creating option menus
dd_opts = ttk.OptionMenu(cm, cm.var_opts, cm.options[0], *cm.options, command=displayOptions)
dd_wind = ttk.OptionMenu(cm, cm.var_wind, cm.opt_wind[0], *cm.opt_wind)
dd_nfft = ttk.OptionMenu(cm, cm.var_nfft, cm.opt_nfft[0], *cm.opt_nfft)
dd_meth = ttk.OptionMenu(cm, cm.var_meth, cm.opt_meth[0], *cm.opt_meth)
dd_pass = ttk.OptionMenu(cm, cm.var_pass, cm.opt_pass[0], *cm.opt_pass)
dd_filt = ttk.OptionMenu(cm, cm.var_filt, cm.opt_filt[0], *cm.opt_filt)
# size of the OptionMenus
dd_opts.config(width=16)
dd_wind.config(width=18, state='disabled')
dd_nfft.config(width=18, state='disabled')
dd_meth.config(width=18, state='disabled')
dd_pass.config(width=18, state='disabled')
dd_filt.config(width=18, state='disabled')
# positioning OptionMenus
dd_opts.grid(column=2, row=0, sticky=tk.EW, padx=5)
dd_wind.grid(column=1, row=1, sticky=tk.EW, padx=5)
dd_nfft.grid(column=1, row=3, sticky=tk.EW, padx=5)
dd_meth.grid(column=1, row=10, sticky=tk.EW, padx=5)
dd_pass.grid(column=3, row=2, sticky=tk.EW, padx=5)
dd_filt.grid(column=3, row=7, sticky=tk.EW, padx=5)
###########
# METHODS #
###########
# Updates the OptionMenu 'om' with the option list 'opt' and variable 'var' passed as a parameter
def updateOptionMenu(self, cm, dd_nfft):
menu = dd_nfft["menu"]
menu.delete(0, "end")
for o in cm.opt_nfft:
menu.add_command(label=o, command=lambda value=o: cm.var_nfft.set(value))
cm.var_nfft.set(cm.opt_nfft[0])
def yticks(self, minfreq, maxfreq):
freq = maxfreq-minfreq
if freq <=100:
plt.yticks(np.arange(minfreq,maxfreq,20))
elif freq <=1000:
plt.yticks(np.arange(minfreq,maxfreq,100))
else:
x = freq//1000
y = x//8
plt.yticks(np.arange(minfreq,maxfreq,1000*(y+1)))
def colorBar(self, fig, x, img):
fig.subplots_adjust(right=0.9) # leave space for the color bar
sub_ax = plt.axes([0.91, 0.12, 0.02, x]) # add a small custom axis (left, bottom, width, height)
fig.colorbar(img, cax=sub_ax, format='%+2.0f dB') # %4.2e, {x:.2e}
def createSpanSelector(self, ax):
# Plays the audio of the selected fragment of the fragment
def listenFragFrag(xmin, xmax):
ini, end = np.searchsorted(self.time, (xmin, xmax))
selectedAudio = self.audio[ini:end+1]
sd.play(selectedAudio, self.fs)
span = SpanSelector(ax, listenFragFrag, 'horizontal', useblit=True, interactive=True, drag_from_anywhere=True)
return span
# def addLoadButton(self, fig, ax, fs, time, audio, name):
# # Takes the selected fragment and opens the control menu when clicked
# def load(event):
# if self.selectedAudio.shape == (1,):
# self.createControlMenu(self, name, fs, audio)
# else:
# self.createControlMenu(self, name, fs, self.selectedAudio)
# plt.close(fig)
# # Adds a 'Load' button to the figure
# axload = fig.add_axes([0.8, 0.01, 0.09, 0.05]) # [left, bottom, width, height]
# but_load = Button(axload, 'Load')
# but_load.on_clicked(load)
# axload._but_load = but_load # reference to the Button (otherwise the button does nothing)
# def listenFrag(xmin, xmax):
# ini, end = np.searchsorted(time, (xmin, xmax))
# self.selectedAudio = audio[ini:end+1]
# sd.play(self.selectedAudio, fs)
# self.span = SpanSelector(ax, listenFrag, 'horizontal', useblit=True, interactive=True, drag_from_anywhere=True)
#####################
# CALCULATE METHODS #
#####################
def calculateWaveform(self, ax):
ax.plot(self.time, self.audio)
ax.axhline(y=0, color='black', linewidth='0.5', linestyle='--') # draw an horizontal line in y=0.0
ax.set(xlim=[0, self.duration], xlabel='Time (s)', ylabel='Amplitude')
def calculateSTFT(self, audioFragWindow, nfft):
stft = np.fft.fft(audioFragWindow, nfft)
return stft[range(int(nfft/2))]
def calculateWindowedSpectrogram(self, cm, ax, window, windSizeSampInt, hopSize, cmap):
nfftUser = cm.var_nfft.get()
draw = cm.var_draw.get()
minfreq = cm.var_minf.get()
maxfreq = cm.var_maxf.get()
# Calculate the linear/mel spectrogram
if draw == 1: # linear
linear = librosa.stft(self.audio, n_fft=nfftUser, hop_length=hopSize, win_length=windSizeSampInt, window=window, center=True, dtype=None, pad_mode='constant')
linear_dB = librosa.amplitude_to_db(np.abs(linear), ref=np.max)
img = librosa.display.specshow(linear_dB, x_axis='time', y_axis='linear', sr=self.fs, fmin=minfreq, fmax=maxfreq, ax=ax, hop_length=hopSize, cmap=cmap)
ax.set(ylim=[minfreq, maxfreq])
else: # mel
mel = librosa.feature.melspectrogram(y=self.audio, sr=self.fs, win_length=windSizeSampInt, n_fft=nfftUser, window=window, fmin=minfreq, fmax=maxfreq, hop_length=hopSize)
mel_dB = librosa.power_to_db(mel)
img = librosa.display.specshow(mel_dB, x_axis='time', y_axis='mel', sr=self.fs, fmin=minfreq, fmax=maxfreq, ax=ax, hop_length=hopSize, cmap=cmap)
ax.set(ylim=[minfreq, maxfreq])
self.yticks(minfreq, maxfreq) # represent the numbers of y axis
return img
def calculateSpectrogram(self, audio, ax, minfreq, maxfreq, draw, cmap):
# Calculate the filtered linear/mel spectrogram filtered
if draw == 1: # linear
linear = librosa.stft(audio, center=True, dtype=None, pad_mode='constant')
linear_dB = librosa.amplitude_to_db(np.abs(linear), ref=np.max)
img = librosa.display.specshow(linear_dB, x_axis='time', y_axis='linear', sr=self.fs, fmin=minfreq, fmax=maxfreq, ax=ax, cmap=cmap)
ax.set(xlim=[0, self.duration], ylim=[minfreq, maxfreq])
else: # mel
mel = librosa.feature.melspectrogram(y=audio, sr=self.fs, fmin=minfreq, fmax=maxfreq)
mel_dB = librosa.power_to_db(mel)
img = librosa.display.specshow(mel_dB, x_axis='time', y_axis='mel', sr=self.fs, fmin=minfreq, fmax=maxfreq, ax=ax, cmap=cmap)
ax.set(xlim=[0, self.duration], ylim=[minfreq, maxfreq])
return img
def calculateSC(self, audioFragWindow):
magnitudes = np.abs(np.fft.rfft(audioFragWindow)) # magnitudes of positive frequencies
length = len(audioFragWindow)
freqs = np.abs(np.fft.fftfreq(length, 1.0/self.fs)[:length//2+1]) # positive frequencies
return np.sum(magnitudes*freqs)/np.sum(magnitudes) # return weighted mean
def calculateSTE(self, sig, win, windSizeSampInt):
window1 = signal.get_window(win, windSizeSampInt)
window = window1 / len(window1)
return signal.convolve(sig**2, window**2, mode='same')
def calculatePitch(self, method, minpitch, maxpitch, maxCandidates):
# Convert the numpy array containing the audio fragment into a wav file
write('wav/frag.wav', self.fs, self.audio) # generates a wav file in the current folder
silenceTh, voiceTh, octaveCost, octJumpCost, vcdUnvcdCost, accurate = self.adse.getAutocorrelationVars()
if accurate == 1: accurate_bool = True
else: accurate_bool = False
# Calculate the pitch of the generated wav file using parselmouth
snd = parselmouth.Sound('wav/frag.wav')
if method == 'Autocorrelation':
pitch = snd.to_pitch_ac(pitch_floor=minpitch,
max_number_of_candidates=maxCandidates,
very_accurate=accurate_bool,
silence_threshold=silenceTh,
voicing_threshold=voiceTh,
octave_cost=octaveCost,
octave_jump_cost=octJumpCost,
voiced_unvoiced_cost=vcdUnvcdCost,
pitch_ceiling=maxpitch)
elif method == 'Cross-correlation':
pitch = snd.to_pitch_cc(pitch_floor=minpitch,
max_number_of_candidates=maxCandidates,
very_accurate=accurate_bool,
silence_threshold=silenceTh,
voicing_threshold=voiceTh,
octave_cost=octaveCost,
octave_jump_cost=octJumpCost,
voiced_unvoiced_cost=vcdUnvcdCost,
pitch_ceiling=maxpitch)
elif method == 'Subharmonics':
maxFreqComp, maxSubharm, compFactor, pointsPerOct = self.adse.getSubharmonicsVars()
pitch = snd.to_pitch_shs(minimum_pitch=minpitch,
max_number_of_candidates=maxCandidates,
maximum_frequency_component=maxFreqComp,
max_number_of_subharmonics=maxSubharm,
compression_factor=compFactor,
ceiling=maxpitch,
number_of_points_per_octave=pointsPerOct)
elif method == 'Spinet':
windLen, minFiltFreq, maxFiltFreq, numFilters = self.adse.getSpinetVars()
pitch = snd.to_pitch_spinet(window_length=windLen,
minimum_filter_frequency=minFiltFreq,
maximum_filter_frequency=maxFiltFreq,
number_of_filters=numFilters,
ceiling=maxpitch,
max_number_of_candidates=maxCandidates)
pitch_values = pitch.selected_array['frequency'] # extract selected pitch contour
pitch_values[pitch_values==0] = np.nan # replace unvoiced samples by NaN to not plot
return pitch, pitch_values
def designFilter(self, fcut1, fcut2, p, filter, type):
gpass = 3
gstop = 40
# Design filter
if type == 'Lowpass' or type == 'Highpass':
wp = fcut1
ws = fcut2
if filter == 'Butterworth':
N, Wn = signal.buttord(wp, ws, gpass, gstop, fs=self.fs)
b, a = signal.butter(N, Wn, btype=type, fs=self.fs)
elif filter == 'Elliptic':
N, Wn = signal.ellipord(wp, ws, gpass, gstop, fs=self.fs)
b, a = signal.ellip(N, gpass, gstop, Wn, btype=type, fs=self.fs)
elif filter == 'Chebyshev I':
N, Wn = signal.cheb1ord(wp, ws, gpass, gstop, fs=self.fs)
b, a = signal.cheby1(N, gpass, Wn, btype=type, fs=self.fs)
elif filter == 'Chebyshev II':
N, Wn = signal.cheb2ord(wp, ws, gpass, gstop, fs=self.fs)
b, a = signal.cheby2(N, gstop, Wn, btype=type, fs=self.fs)
# elif filter == 'FIR least-squares':
# coeffs = signal.firls(fs=self.audiofs)
ws1 = fcut1
ws2 = fcut2
elif type == 'Bandpass' or type == 'Bandstop':
delta1 = fcut1 * (p/100) # 1st transition band
delta2 = fcut2 * (p/100) # 2nd transition band
wp1 = fcut1 + delta1
wp2 = fcut2 - delta2
ws1 = fcut1 - delta1
ws2 = fcut2 + delta2
if filter == 'Butterworth':
N, Wn = signal.buttord([wp1,wp2], [ws1,ws2], gpass, gstop, fs=self.fs)
b, a = signal.butter(N, Wn, btype=type, fs=self.fs)
elif filter == 'Elliptic':
N, Wn = signal.ellipord([wp1,wp2], [ws1,ws2], gpass, gstop, fs=self.fs)
b, a = signal.ellip(N, gpass, gstop, Wn, btype=type, fs=self.fs)
elif filter == 'Chebyshev I':
N, Wn = signal.cheb1ord([wp1,wp2], [ws1,ws2], gpass, gstop, fs=self.fs)
b, a = signal.cheby1(N, gpass, Wn, btype=type, fs=self.fs)
elif filter == 'Chebyshev II':
N, Wn = signal.cheb2ord([wp1,wp2], [ws1,ws2], gpass, gstop, fs=self.fs)
b, a = signal.cheby2(N, gstop, Wn, btype=type, fs=self.fs)
# elif filter == 'FIR least-squares':
# coeffs = signal.firls(fs=self.audiofs)
filteredSignal = signal.lfilter(b, a, self.audio)
return filteredSignal, ws1, ws2, b, a
################
# PLOT METHODS #
################
# Plots the waveform and the Fast Fourier Transform (FFT) of the fragment
def plotFT(self, cm):
self.figFT, ax = plt.subplots(2, figsize=(12,6))
self.figFT.suptitle('Fourier Transform')
plt.subplots_adjust(hspace=.3) # to avoid overlapping between xlabel and title
self.figFT.canvas.manager.set_window_title(self.fileName+'-FT')
fft = np.fft.fft(self.audio) / self.lenAudio # Normalize amplitude
fft2 = fft[range(int(self.lenAudio/2))] # Exclude sampling frequency
values = np.arange(int(self.lenAudio/2))
frequencies = values / (self.lenAudio/self.fs) # values / time period
# 'self.time' and 'self.audio' need to have the same first dimension
if len(self.time) < len(self.audio):
self.audio = self.audio[:-1].copy() # delete last element of the numpy array
elif len(self.time) > len(self.audio):
self.time = self.time[:-1].copy() # delete last element of the numpy array
self.calculateWaveform(ax[0])
ax[1].plot(frequencies, 20*np.log10(abs(fft2)))
ax[1].set(xlim=[0, max(frequencies)], xlabel='Frequency (Hz)', ylabel='Amplitude (dB)')
self.aux.saveasWavCsv(cm, self.figFT, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.aux.saveasCsv(self.figFT, frequencies, 20*np.log10(abs(fft2)), 0.05, 'FT') # save FT as csv
# TO-DO: connect figFrag with w1Button in signalVisualizer
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
self.figFT.show() # show the figure
def plotSTFT(self, cm, stft, frequencies, title):
fig, ax = plt.subplots(2, figsize=(12,6))
fig.suptitle('Short Time Fourier Transform')
plt.subplots_adjust(hspace=.3) # to avoid overlapping between xlabel and title
fig.canvas.manager.set_window_title(str(self.fileName)+'-STFT-'+title) # set title to the figure window
self.calculateWaveform(ax[0])
line1, = ax[1].plot(frequencies, 20*np.log10(abs(stft)))
ax[1].set(xlim=[0, max(frequencies)], xlabel='Frequency (Hz)', ylabel='Amplitude (dB)')
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.aux.saveasCsv(fig, frequencies, 20*np.log10(abs(stft)), 0.05, 'STFT') # save FT as csv
self.cursor = Cursor(ax[0], horizOn=False, useblit=True, color='black', linewidth=1)
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
return ax, line1
def plotSpectrogram(self, cm, window, windSizeSampInt, hopSize, cmap, title):
fig = plt.figure(figsize=(12,6))
gs = fig.add_gridspec(2, hspace=0)
ax = gs.subplots(sharex=True)
fig.suptitle('Spectrogram')
fig.canvas.manager.set_window_title(str(self.fileName)+'-Spectrogram-'+title) # set title to the figure window
# Hide x labels and tick labels for all but bottom plot.
for a in ax:
a.label_outer()
# Calculate the linear/mel spectrogram
img = self.calculateWindowedSpectrogram(cm, ax[1], window, windSizeSampInt, hopSize, cmap)
self.colorBar(fig, 0.36, img)
self.calculateWaveform(ax[0])
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.multicursor = MultiCursor(fig.canvas, (ax[0], ax[1]), color='black', lw=1)
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
plt.show() # show the figure
def plotSTFTspect(self, cm, stft, frequencies, window, windSizeSampInt, hopSize, cmap, title):
fig = plt.figure(figsize=(12,6))
ax1 = plt.subplot(311) # waveform
ax2 = plt.subplot(312) # stft
ax3 = plt.subplot(313, sharex=ax1) # spectrogram
plt.subplots_adjust(hspace=.4) # to avoid overlapping between xlabel and title
fig.suptitle('STFT + Spectrogram')
fig.canvas.manager.set_window_title(str(self.fileName)+'-STFT+Spectrogram-'+title) # set title to the figure window
self.calculateWaveform(ax1)
line1, = ax2.plot(frequencies, 20*np.log10(abs(stft)))
ax2.set(xlim=[0, max(frequencies)], xlabel='Frequency (Hz)', ylabel='Amplitude (dB)')
# Calculate the linear/mel spectrogram
img = self.calculateWindowedSpectrogram(cm, ax3, window, windSizeSampInt, hopSize, cmap)
self.colorBar(fig, 0.17, img)
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.65, self.fs) # save waveform as csv
self.aux.saveasCsv(fig, frequencies, 20*np.log10(abs(stft)), 0.35, 'STFT') # save STFT as csv
self.multicursor = MultiCursor(fig.canvas, (ax1, ax3), color='black', lw=1)
self.span = self.createSpanSelector(ax1) # Select a fragment with the cursor and play the audio of that fragment
return ax1, ax2, ax3, line1
def plotSC(self, cm, audioFragWind2, window, windSizeSampInt, nfftUser, overlapSamp, hopSize, cmap, title):
fig = plt.figure(figsize=(12,6))
ax1 = plt.subplot(311) # waveform
ax2 = plt.subplot(312) # power spectral density
ax3 = plt.subplot(313, sharex=ax1) # spectrogram with spectral centroid
plt.subplots_adjust(hspace=.6) # to avoid overlapping between xlabel and title
fig.suptitle('Spectral Centroid')
fig.canvas.manager.set_window_title(str(self.fileName)+'-SpectralCentroid-'+title) # set title to the figure window
# Calculate the spectral centroid in the FFT as a vertical line
spectralC = self.calculateSC(audioFragWind2)
scValue = str(round(spectralC, 2)) # take only two decimals
# Calculate the spectral centroid in the log power linear/mel spectrogram
sc = librosa.feature.spectral_centroid(y=self.audio, sr=self.fs, n_fft=nfftUser, hop_length=hopSize, window=window, win_length=windSizeSampInt)
times = librosa.times_like(sc, sr=self.fs, hop_length=hopSize, n_fft=nfftUser)
self.calculateWaveform(ax1)
_, freqs = ax2.psd(audioFragWind2, NFFT=windSizeSampInt, pad_to=nfftUser, Fs=self.fs, window=window, noverlap=overlapSamp)
ax2.axvline(x=spectralC, color='r', linewidth='1') # draw a vertical line in x=value of the spectral centroid
ax2.set(xlim=[0, max(freqs)], xlabel='Frequency (Hz)', ylabel='Power spectral density (dB/Hz)', title='Power spectral density using fft, spectral centroid value is '+ scValue)
# Calculate the linear/mel spectrogram and the spectral centroid
img = self.calculateWindowedSpectrogram(cm, ax3, window, windSizeSampInt, hopSize, cmap)
self.colorBar(fig, 0.17, img)
line1, = ax3.plot(times, sc.T, color='w') # draw the white line (sc)
ax3.set(xlim=[0, self.duration], title='log Power spectrogram')
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.65, self.fs) # save waveform as csv
self.aux.saveasCsv(fig, times, sc.T, 0.05, 'SC') # save the white line as csv
self.multicursor = MultiCursor(fig.canvas, (ax1, ax3), color='black', lw=1)
self.span = self.createSpanSelector(ax1) # Select a fragment with the cursor and play the audio of that fragment
return ax1, ax2, ax3, line1
def plotSTE(self, cm, windType1, windSizeSampInt, title):
fig = plt.figure(figsize=(12,6))
gs = fig.add_gridspec(2, hspace=0)
ax = gs.subplots(sharex=True)
fig.suptitle('Short Time Energy')
fig.canvas.manager.set_window_title(str(self.fileName)+'-STE-'+title) # set title to the figure window
# Hide x labels and tick labels for all but bottom plot.
for a in ax:
a.label_outer()
# Calculate the Short-Time-Energy
signal = np.array(self.audio, dtype=float)
time = np.arange(len(signal)) * (1.0/self.fs)
ste = self.calculateSTE(signal, windType1, windSizeSampInt)
self.calculateWaveform(ax[0])
ax[1].plot(time, ste)
ax[1].set(xlim=[0, self.duration], xlabel='Time (s)', ylabel='Amplitude (dB)')
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.aux.saveasCsv(fig, time, ste, 0.05, 'STE') # save STE as csv
self.multicursor = MultiCursor(fig.canvas, (ax[0], ax[1]), color='black', lw=1)
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
plt.show() # show the figure
def plotPitch(self, cm, cmap):
method = cm.var_meth.get()
minpitch = cm.var_minp.get()
maxpitch = cm.var_maxp.get()
showSpec = cm.var_spec.get()
maxCandidates, drawStyle = self.adse.getVariables()
fig = plt.figure(figsize=(12,6))
gs = fig.add_gridspec(2, hspace=0)
ax = gs.subplots(sharex=True)
fig.suptitle('Pitch measurement overtime')
fig.canvas.manager.set_window_title('Pitch-Method_'+ str(method) +'-PitchFloor_'+ str(minpitch) + 'Hz-PitchCeiling_'+ str(maxpitch) + 'Hz') # set title to the figure window
# Hide x labels and tick labels for all but bottom plot.
for a in ax:
a.label_outer()
pitch, pitch_values = self.calculatePitch(method, minpitch, maxpitch, maxCandidates)
if showSpec == 1:
if math.isnan(min(pitch_values)) and math.isnan(max(pitch_values)):
text = "Cannot draw the spectrogram because minimum and maximum values of the samples of the pitch are unvoiced."
tk.messagebox.showerror(parent=cm, title="Unvoiced samples", message=text) # show error
else:
img = self.calculateSpectrogram(self.audio, ax[1], min(pitch_values), max(pitch_values), 1, cmap)
self.colorBar(fig, 0.36, img)
color = 'w'
else: color = '#1f77b4'
if drawStyle == 1: draw = '-'
else: draw = 'o'
self.calculateWaveform(ax[0])
ax[1].plot(pitch.xs(), pitch_values, draw, color=color)
ax[1].set(xlim=[0, self.duration], xlabel='Time (s)', ylabel='Frequency (Hz)')
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.aux.saveasCsv(fig, pitch.xs(), pitch_values, 0.05, 'Pitch') # save Pitch as csv
self.multicursor = MultiCursor(fig.canvas, (ax[0], ax[1]), color='black', lw=1)
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
plt.show() # show the figure
def plotFiltering(self, cm, cmap):
# fundfreq = cm.var_fund.get()
# center = cm.var_cent.get()
p = 10
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
filter = cm.var_filt.get() # butterworth, elliptic...
type = cm.var_pass.get() # # lowpass, highpass, bandpass or bandstop
draw = cm.var_draw.get()
fig = plt.figure(figsize=(12,6))
gs = fig.add_gridspec(2, hspace=0)
ax = gs.subplots(sharex=True)
fig.suptitle('Filtering')
fig.canvas.manager.set_window_title('Filtering-'+str(filter)+'-'+str(type)+'-Fcut1_'+str(fcut1)+'Hz-Fcut2_'+str(fcut2)+'Hz') # set title to the figure window
# figFragFilt.canvas.manager.set_window_title('Filtering-FundFreqMult_'+ str(fundfreq) +'-Center_'+ str(center) + '-Fcut1_'+ str(fcut1) + 'Hz-Fcut2_'+ str(fcut2) + 'Hz' + '-Filter_'+ str(filter)) # set title to the figure window
# Hide x labels and tick labels for all but bottom plot.
for a in ax:
a.label_outer()
filteredSignal, minfreq, maxfreq, _, _ = self.designFilter(fcut1, fcut2, p, filter, type)
# Calculate the linear/mel spectrogram
img = self.calculateSpectrogram(filteredSignal, ax[1], minfreq, maxfreq, draw, cmap)
self.yticks(minfreq, maxfreq) # represent the numbers of y axis
self.colorBar(fig, 0.36, img)
self.calculateWaveform(ax[0])
self.aux.saveasWavCsv(cm, fig, self.time, self.audio, 0.5, self.fs) # save waveform as csv
self.span = self.createSpanSelector(ax[0]) # Select a fragment with the cursor and play the audio of that fragment
# self.addLoadButton(fig, ax[0], self.fs, self.time, filteredSignal, self.fileName+str(' (filtered)'))
plt.show() # show the figure
def plotFiltFreqResponse(self, cm):
p = 10
fcut1 = cm.var_cut1.get()
fcut2 = cm.var_cut2.get()
filter = cm.var_filt.get() # butterworth, elliptic...
type = cm.var_pass.get() # # lowpass, highpass, bandpass or bandstop
fig, ax = plt.subplots(2, figsize=(9,7))
plt.subplots_adjust(hspace=.3) # to avoid overlapping between xlabel and title
fig.canvas.manager.set_window_title('Filter frequency response') # set title to the figure window
_, _, _, b, a = self.designFilter(fcut1, fcut2, p, filter, type)
# Calculate the filter frequency response
w, h = signal.freqz(b, a, fs=self.fs) # w: frequencies in Hz, h: frequency response
# w_rad, _ = signal.freqz(b, a) # w_rad: frequencies in rad/samples
h = signal.TransferFunction(b, a)