Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何从用户处接受文件名并用python保存声音文件_Python 3.x_User Interface_Tkinter_Pyaudio - Fatal编程技术网

Python 3.x 如何从用户处接受文件名并用python保存声音文件

Python 3.x 如何从用户处接受文件名并用python保存声音文件,python-3.x,user-interface,tkinter,pyaudio,Python 3.x,User Interface,Tkinter,Pyaudio,我正在尝试用python录制pyaudio中的声音,并为此制作gui。 当我使用datetime库并给出文件名例如:sound_2020_21_04_03_40.wav(当前日期、时间)时,我的代码运行良好,但当我尝试使用tkinter从用户处获取文件名(从tkinter.filedialog导入asksaveasfile)时,它正在保存声音文件,但它是空的,只有0字节 有人能帮我吗。这是我的停止按钮的编码部分,它终止代码并保存文件 import tkinter as tk import thr

我正在尝试用python录制pyaudio中的声音,并为此制作gui。 当我使用datetime库并给出文件名例如:sound_2020_21_04_03_40.wav(当前日期、时间)时,我的代码运行良好,但当我尝试使用tkinter从用户处获取文件名(从tkinter.filedialog导入asksaveasfile)时,它正在保存声音文件,但它是空的,只有0字节

有人能帮我吗。这是我的停止按钮的编码部分,它终止代码并保存文件

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  

    frames = []  
    def __init__(self, master):
        self.isrecording = False
        myFont = font.Font(weight="bold")
        self.button1 = tk.Button(main, text='Record',command=self.startrecording,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.button2['font'] = myFont
        self.button1.place(x=30, y=30)
        self.button2.place(x=280, y=30)

    def startrecording(self):
        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)
        self.isrecording = 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='w',filetypes = (("audio file","*.wav"),("all files","*.*")),defaultextension=".wav")

        wf = wave.open(self.filename, 'wb')
        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 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()


图片在这里


奇怪的是,没有出现异常,因为当您调用
askopenfile(…)
时,它返回一个文件对象(并打开一个空文件进行读取-您看到的文件),但
wave.open(…)
需要一个文件名。要获得它,您需要使用
askopenfilename(…)
而不是
askopenfile(…)
。别忘了在代码顶部导入
askopenfilename

以下是完整的代码(我已经根据PEP8对其进行了重构):


创建空文件是因为
askopenfile(…)
在调用后创建了一个文件。您的问题是
pyaudio
无法保存文件。@DemianWolf如何解决此问题。您需要导入
askopenfilename(…)
而不是
askopenfile(…)
。请参阅答案中的详细信息和完整代码。
wave.open(filename,…)
filename可以是字符串或文件对象。
import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *
import tkinter.font as font
from tkinter.filedialog import asksaveasfilename


class App():
    chunk = 1024
    sample_format = pyaudio.paInt16
    channels = 2
    fs = 44100

    frames = []

    def __init__(self, master):
        self.isrecording = False
        myFont = font.Font(weight="bold")
        self.button1 = tk.Button(main, text='Record', command=self.startrecording,
                                 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.button2['font'] = myFont
        self.button1.place(x=30, y=30)
        self.button2.place(x=280, y=30)

    def startrecording(self):
        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)
        self.isrecording = True

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

    def stoprecording(self):
        self.isrecording = False
        print('recording complete')

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

        wf = wave.open(self.filename, 'wb')
        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 record(self):
        while self.isrecording:
            data = self.stream.read(self.chunk)
            self.frames.append(data)
            print("does it")


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