【问题标题】:Tkinter start/stop button for recording audio in Python用于在 Python 中录制音频的 Tkinter 开始/停止按钮
【发布时间】:2020-04-28 08:59:30
【问题描述】:

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

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

  1. 我不能使用 while Truestatement 或 time.sleep()function 因为它会破坏 Tkinter mainloop()

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

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

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

我知道某处必须有一个循环,但我不知道在哪里(以及如何)。

【问题讨论】:

  • [python][tkinter] start stop中选择一个
  • 我会使用全局file 变量并使用file = open()。然后我会在stop()中使用file.stop_recording()
  • 这是一个带有开始/停止按钮的 GUI 记录器示例:rec_gui.py。它没有使用 PyAudio,但它可能会有所帮助。

标签: python audio tkinter pyaudio recording


【解决方案1】:

我会使用普通的而不是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() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2014-01-21
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多