how to start and stop recording with single button

无人久伴 提交于 2020-03-05 06:06:11

问题


I am having an issue with this code, when I try to run this code with two separate buttons it runs fine but when I try to use only a single button to start and stop the recording by changing its text(label) to start and stop recording the code does not work. The text of the button changes but it does not record anything.

import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *
import tkinter.font as font
from tkinter.filedialog import asksaveasfile

class App():
    chunk = 1024 
    sample_format = pyaudio.paInt16 
    channels = 2
    fs = 44100 
    def __init__(self,master):

        self.isrecording = False
        self.frames = []
        myFont = font.Font(weight="bold")
        self.button1 = tk.Button(main, text='Record',command=self.change,height=2,width=20,bg='#0052cc', fg='#ffffff')
        #self.button2 = tk.Button(main, text='stop',command=self.stoprecording,height=2,width=20,bg='#0052cc', fg='#ffffff')
        self.button1['font'] = myFont
        self.button1.place(x=30, y=30)

    def startrecording(self):

        self.isrecording = True
        self.p = pyaudio.PyAudio()  
        self.stream = self.p.open(format=self.sample_format,channels=self.channels,rate=self.fs,frames_per_buffer=self.chunk,input=True)


        print('Recording')
        t = threading.Thread(target=self.record)
        t.start()
    def stoprecording(self):

        self.isrecording = False
        print('recording complete')


        self.filename = asksaveasfile(initialdir = "/",title = "Save as",mode='wb',filetypes = (("audio file","*.wav"),("all files","*.*")),defaultextension=".wav")

        wf = wave.open(self.filename)
        wf.setnchannels(self.channels)
        wf.setsampwidth(self.p.get_sample_size(self.sample_format))
        wf.setframerate(self.fs)
        wf.writeframes(b''.join(self.frames))
        wf.close()
        main.destroy()
    def change(self):
        if self.button1['text'] == 'Record':
            self.startrecording()
            self.isrecording = True
            self.button1.config(text="Stop")
        else:
            self.stoprecording()
            self.isrecording = False
            self.button1.config(text="Record")
    def record(self):

        while self.isrecording:
            data = self.stream.read(self.chunk)
            self.frames.append(data)



main = tk.Tk()
main.title('recorder')
main.geometry('520x120')
app = App(main)
main.mainloop()

error image

来源:https://stackoverflow.com/questions/60370314/how-to-start-and-stop-recording-with-single-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!