python錄音文件(別人的代碼自己修改)
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 ="結(jié)束錄音", 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()
運(yùn)行比較良好。能夠把語音變成wav文件。
下一步準(zhǔn)備整合成為傻瓜讀書軟件的一個(gè)部分。將偷懶進(jìn)行到底。