-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickPlayer.py
218 lines (176 loc) · 7.14 KB
/
quickPlayer.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
import sys, os
import asyncio
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pyaudio
import wave
import tkinter as tk
from tkinter import *
from tkinter import filedialog as tkFileDialog
from tkinter import messagebox as tkMessageBox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import Event
def quickPlayer(soundfile,data,stamps,names,h=128,onlyValues=False,regions=None):
"""
USAGE:
press spacebar to start/stop playing.
Navigate by clicking on plot, and with 'zoom' and 'pan' features of the toolbar.
Zoom: Click and drag. Right click to zoom out.
Plot and player will automatically follow if zoomed. But if zoomed too much, it may cause stuttering.
Panning while audio is being played will cause stuttering.
ARGS:
onlyValues: If provided time stamps does not have IDs or names (so just lines to be drawn), this should be True. Manually annotated files will have IDs and names for the stamps .
soundfile: sound file to be played
data: data that shown on the player plot
stamps: lines will be drawed on these points on the data
h: hopsize
size(data) * h = size(sound) If you pass audio samples as data, h (hop size) should be 1.
"""
wf = wave.open(soundfile,'rb')
parent = Tk()
chunk_size = 2048
sem = asyncio.Semaphore()
play_mode = tk.BooleanVar(parent, False)
fig = plt.figure(figsize=(18,7), dpi=100)
mainplot = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, parent)
canvaswidget = canvas.get_tk_widget()
canvaswidget.grid(row=2,column=0,columnspan=5, sticky=W)
toolbarFrame = Frame(master=parent)
toolbarFrame.grid(row=3,column=0, columnspan=7)
toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
toolbar.update()
canvas._tkcanvas.grid(row=2,column=0, columnspan = 7, sticky=W)
global background
background = canvas.copy_from_bbox(mainplot.bbox)
cursor = mainplot.axvline(color="k", animated=True)
cursor.set_xdata(0)
for d in data:
if d.ndim == 2:
ymax = d.shape[1]
ymin = 0
mainplot.pcolormesh(np.arange(d.shape[0]), np.arange(d.shape[1]), np.transpose(d))
if d.ndim == 1:
ymax = np.max(data[0])
ymin= np.min(data[0])
mainplot.plot(d)
global x0,x1
x0,x1 = mainplot.get_xlim()
p = pyaudio.PyAudio()
def callbackstream(in_data, frame_count, time_info, status):
sem.acquire()
data = wf.readframes(frame_count)
parent.event_generate("<<playbackmove>>",when="now")
sem.release()
return (data, pyaudio.paContinue)
_callbackstream = callbackstream
def initStream():
global stream
stream = p.open(format=8,
channels=1,
rate=44100,
output=True,
stream_callback=_callbackstream,
start = True,
frames_per_buffer = chunk_size)
def playsound(event=None):
if sem.locked():
return
if play_mode.get() == True:
# this is broken
global stream
stream.close()
play_mode.set(False)
else:
try:
initStream()
play_mode.set(True)
except:
print("play failed")
def playbackMove(event=None): # move cursor by audio chunk size
global x0,x1
global background
incr = (chunk_size)//h
nextpos = cursor.get_xdata()+incr
cursor.set_xdata(nextpos)
updateCursor()
if (x1-nextpos)<0:
mainplot.set_xlim(x1,x1+x1-x0)
canvas.draw()
toolbar.push_current()
background = canvas.copy_from_bbox(mainplot.bbox)
x0,x1 = mainplot.get_xlim()
def new_release_zoom(*args,**kwargs):
global x0,x1
release_zoom_orig(*args, **kwargs)
s = 'toolbar_event'
event = Event(s,canvas)
canvas.callbacks.process(s, Event('toolbar_event',canvas))
x0,x1 = mainplot.get_xlim()
def new_release_pan(*args, **kwargs):
global x0,x1
release_pan_orig(*args, **kwargs)
s = 'toolbar_event'
event = Event(s,canvas)
canvas.callbacks.process(s, Event('toolbar_event',canvas))
x0,x1 = mainplot.get_xlim()
def new_update_view(*args, **kwargs):
global x0,x1
_update_view_orig(*args, **kwargs)
s = 'toolbar_event'
event = Event(s,canvas)
canvas.callbacks.process(s, Event('toolbar_event',canvas))
x0,x1 = mainplot.get_xlim()
def handle_toolbar(event):
global x0,x1
canvas.draw()
global background
background = canvas.copy_from_bbox(mainplot.bbox)
def onclick(event):
if (toolbar._active == 'ZOOM' or toolbar._active == 'PAN'):
pass
else:
cursor.set_xdata(event.xdata)
wf.setpos(int(event.xdata*h))
updateCursor()
def updateCursor():
canvas.restore_region(background)
mainplot.draw_artist(cursor)
canvas.blit(mainplot.bbox)
parent.bind("<space>",playsound)
parent.bind("<<playbackmove>>",playbackMove)
release_zoom_orig = toolbar.release_zoom
toolbar.release_zoom = new_release_zoom
release_pan_orig = toolbar.release_pan
toolbar.release_pan = new_release_pan
_update_view_orig = toolbar._update_view
toolbar._update_view = new_update_view
canvas.mpl_connect('toolbar_event', handle_toolbar)
cid1 = canvas.mpl_connect("button_press_event", onclick)
canvas.draw()
colors = ['c','m','y','r','#FFBD33','#924A03','#D00000','#D000D0','#6800D0','#095549','b','r','r']
if onlyValues:
for i in range(len(stamps)):
mainplot.draw_artist(mainplot.vlines(x=np.array(stamps[i])/h,color=colors[i],ymin=ymin,ymax=ymax,label=names[i]))
mainplot.legend(loc="upper left")
else:
for i in range(len(stamps)):
for j in stamps[i]:
mainplot.draw_artist(mainplot.axvline(x=j[1]/h,ymin=ymin,ymax=ymax,color=colors[i]))
mainplot.text(j[1]/h+2, (0.8*ymax)+(i*0.04), names[i] + str(j[0]), bbox=dict(fill=False, edgecolor=colors[i], linewidth=1))
if regions!=None:
for r in regions:
mainplot.fill_betweenx([ymin,ymax], r[0],r[1], facecolor='blue', alpha=0.5)
canvas.draw()
background = canvas.copy_from_bbox(mainplot.bbox)
parent.mainloop()
for func in [stream.close,
wf.close,
p.terminate,
parent.destroy]:
try:
func()
except:
pass
return