import tkinter
from tkinter import *
from tkinter import ttk
import os
import pyaudio
import time
import threading
import wave
class Recorder():
def __init__(self, chunk=1024, channels=1, rate=64000):
self.CHUNK = chunk
self.FORMAT = pyaudio.paInt16
self.CHANNELS = channels
self.RATE = rate
self._running = True
self._frames = []
def start(self):
threading._start_new_thread(self.__recording, ())
def __recording(self):
self._running = True
self._frames = []
p = pyaudio.PyAudio()
stream = p.open(format=self.FORMAT,
channels=self.CHANNELS,
rate=self.RATE,
input=True,
frames_per_buffer=self.CHUNK)
while(self._running):
data = stream.read(self.CHUNK)
self._frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
def stop(self):
self._running = False
def save(self, filename):
p = pyaudio.PyAudio()
if not filename.endswith(".wav"):
filename = filename + ".wav"
wf = wave.open(filename, 'wb')
wf.setnchannels(self.CHANNELS)
wf.setsampwidth(p.get_sample_size(self.FORMAT))
wf.setframerate(self.RATE)
wf.writeframes(b''.join(self._frames))
wf.close()
print("Saved")
def startad():
global rec
rec = Recorder()
begin = time.time()
print("Start recording")
rec.start()
def stopad():
print("Stop recording")
rec.stop()
fina = time.time()
def savead():
rec.save("1.wav")
root=Tk()
Button1=tkinter.Button(root, text ="开始录音", command =startad)
Button1.grid(row=0,column=0,padx=20,pady=20)
Button2=tkinter.Button(root, text ="结束录音", command =stopad)
Button2.grid(row=0,column=1,padx=20,pady=20)
Button3=tkinter.Button(root, text ="保存录音", command = savead)
Button3.grid(row=0,column=2,padx=20,pady=20)
root.mainloop()
运行比较良好。能够把语音变成wav文件。
下一步准备整合成为傻瓜读书软件的一个部分。将偷懒进行到底。