import pyaudio
import wave
# 创建录音类
class Audio():
def __init__(self,chunk=1024,channels=2,rate=44100):
# 设置一些录音是参数
self.chunk = chunk
self.channels = channels #声道数:单声道、双声道
self.rate = rate #取样频率:一秒钟对声音采样的次数
self.running = True
self.frame = []
self.format = pyaudio.paInt16
self.seconds = 5
def run(self):#开始录音函数
self.running = True
self.frame = []
pa = pyaudio.PyAudio()
#查找录音设备
device = self.findDevice(pa)
stream = pa.open(
format = self.format,
channels = self.channels,
rate = self.rate,
input = True,
frames_per_buffer = self.chunk
)
for i in range(0,int(self.rate/self.chunk*self.seconds)):
data = stream.read(self.chunk)
self.frame.append(data)
stream.stop_stream()
stream.close()
pa.terminate()
return
def stop(self):
self.running = False
def save(self,fileName):
pa = pyaudio.PyAudio()
f = wave.open(fileName,'wb')
f.setnchannels(self.channels)
f.setframerate(self.rate)
f.setsampwidth(pa.get_sample_size(self.format))
f.writeframes(b''.join(self.frame))
f.close()
pa.terminate()
if __name__ == '__main__':
print("开始录音:")
audio = Audio()
audio.run()
status = True
while status:
temp = input("按下x结束")
if temp == 'x':
running = False
audio.stop()
audio.save("test.wav")
08-23
08-23
08-23