Tkinter开始/停止按钮,用于在Python中录制音频
我正在编写一个程序,用Tkinter GUI录制音频。对于录制音频本身,我使用以下代码:在非阻塞模式下 现在我想实现一些东西,比如启动/停止按钮,但我觉得我错过了一些东西。以下假设:Tkinter开始/停止按钮,用于在Python中录制音频,python,audio,tkinter,pyaudio,recording,Python,Audio,Tkinter,Pyaudio,Recording,我正在编写一个程序,用Tkinter GUI录制音频。对于录制音频本身,我使用以下代码:在非阻塞模式下 现在我想实现一些东西,比如启动/停止按钮,但我觉得我错过了一些东西。以下假设: 我不能使用while True语句,也不能使用time.sleep()函数,因为它将中断Tkintermainloop() 因此,我可能必须使用全局bool来检查我的start\u recording()函数是否正在运行 我必须以与start\u recording相同的函数调用stop\u recording,因
while True
语句,也不能使用time.sleep()
函数,因为它将中断Tkintermainloop()
bool
来检查我的start\u recording()
函数是否正在运行start\u recording
相同的函数调用stop\u 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()
我知道某个地方一定有一个循环,但我不知道在哪里(以及如何) 使用
而不是我将使用普通
running = rec.open('nonblocking.wav', 'wb')
running.stop_recording()
因此,我将在两个函数中使用它-start
和stop
,并且我不需要任何循环
我只需要全局变量运行
,就可以访问这两个函数中的记录器
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()
从中选择一个,我将使用全局文件变量并使用文件=打开()。然后我会在stop()
中使用file.stop\u recording()
,下面是一个带有开始/停止按钮的GUI记录器示例:。它没有使用PyAudio,但它可能会有所帮助。