我正在编写一个使用Tkinter GUI录制音频的程序。为了录制音频本身,我在无阻塞模式下使用以下代码:https://gist.github.com/sloria/5693955。
现在,我想实现诸如“开始/停止”按钮之类的功能,但感觉好像我错过了某些功能。以下假设:
while True
语句或time.sleep()
函数,因为它将破坏Tkinter的mainloop()
bool
来检查我的start_recording()
函数是否正在运行stop_recording
相同的函数中调用start_recording
,因为两者都必须使用相同的对象root.after()
调用,因为我希望记录是用户定义的。 查找以下问题的代码段:
import tkinter as tk
from tkinter import Button
import recorder
running = False
button_rec = Button(self, text='Aufnehmen', command=self.record)
button_rec.pack()
button_stop = Button(self, text='Stop', command=self.stop)
self.button_stop.pack()
rec = recorder.Recorder(channels=2)
def stop(self):
self.running = False
def record(self):
running = True
if running:
with self.rec.open('nonblocking.wav', 'wb') as file:
file.start_recording()
if self.running == False:
file.stop_recording()
root = tk.Tk()
root.mainloop()
我知道某个地方必须有一个循环,但是我不知道在哪里(以及如何)。
最佳答案
代替with
我将使用正常
running = rec.open('nonblocking.wav', 'wb')
running.stop_recording()
所以我会在两个函数中使用它-
start
和stop
-并且我不需要任何循环。我只需要全局变量
running
即可访问这两个函数中的记录器。import tkinter as tk
import recorder
# --- functions ---
def start():
global running
if running is not None:
print('already running')
else:
running = rec.open('nonblocking.wav', 'wb')
running.start_recording()
def stop():
global running
if running is not None:
running.stop_recording()
running.close()
running = None
else:
print('not running')
# --- main ---
rec = recorder.Recorder(channels=2)
running = None
root = tk.Tk()
button_rec = tk.Button(root, text='Start', command=start)
button_rec.pack()
button_stop = tk.Button(root, text='Stop', command=stop)
button_stop.pack()
root.mainloop()