【发布时间】:2020-04-28 08:59:30
【问题描述】:
我正在编写一个使用 Tkinter GUI 录制音频的程序。对于录制音频本身,我在非阻塞模式下使用此代码:https://gist.github.com/sloria/5693955。
现在我想实现一个开始/停止按钮之类的东西,但感觉我错过了一些东西。以下假设:
我不能使用
while Truestatement 或time.sleep()function 因为它会破坏 Tkintermainloop()因此,我可能不得不使用全局
bool来检查我的start_recording()函数是否正在运行我将不得不在与
start_recording相同的函数中调用stop_recording,因为两者都必须使用相同的对象我不能使用
root.after()呼叫,因为我希望录音是用户定义的。
在下面找到问题的代码sn-p:
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()
我知道某处必须有一个循环,但我不知道在哪里(以及如何)。
【问题讨论】:
-
我会使用全局
file变量并使用file = open()。然后我会在stop()中使用file.stop_recording() -
这是一个带有开始/停止按钮的 GUI 记录器示例:rec_gui.py。它没有使用 PyAudio,但它可能会有所帮助。
标签: python audio tkinter pyaudio recording