Tkinter start/stop 用于在 Python 中录制音频的按钮

Tkinter start/stop button for recording audio in Python

我正在编写一个使用 Tkinter GUI 录制音频的程序。对于录制音频本身,我使用此代码:https://gist.github.com/sloria/5693955 在非阻塞模式下。

现在我想实现类似 start/stop 按钮的东西,但感觉我错过了什么。以下假设:

  1. 我不能使用 while True 语句或 time.sleep() 函数,因为它会破坏 Tkinter mainloop()

  2. 因此,我可能不得不使用全局 bool 来检查我的 start_recording() 函数是否是 运行

  3. 我将不得不在与 start_recording 相同的函数中调用 stop_recording 因为两者都必须使用相同的对象

  4. 我不能使用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()

所以我会在两个函数中使用它 - startstop - 我不需要任何循环。

我只需要全局变量 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()