繁体   English   中英

用于在 Python 中录制音频的 Tkinter 开始/停止按钮

[英]Tkinter start/stop button for recording audio in Python

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

现在我想实现像开始/停止按钮这样的东西,但感觉我错过了一些东西。 以下假设:

  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() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM