# -*- coding: utf-8 -*- import wave import pylab as pl import numpy as np from pyaudio import PyAudio,paInt16 def record(filename): #define of params NUM_SAMPLES = 2000 framerate = 16000 channels = 1 sampwidth = 2 #record time TIME = 10 def save_wave_file(filename, data): ‘‘‘save the date to the wav file‘‘‘ wf = wave.open(filename, ‘wb‘) wf.setnchannels(channels) wf.setsampwidth(sampwidth) wf.setframerate(framerate) wf.writeframes("".join(data)) wf.close() def record_wave(): #open the input of wave pa = PyAudio() stream = pa.open(format = paInt16, channels = 1,rate = framerate, input = True,frames_per_buffer = NUM_SAMPLES) save_buffer = [] count = 0 while count < TIME*4: #read NUM_SAMPLES sampling data string_audio_data = stream.read(NUM_SAMPLES) save_buffer.append(string_audio_data) count += 1 print ‘.‘, print ‘‘ #filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav" save_wave_file(filename, save_buffer) #save_buffer = [] #print filename, "saved" record_wave() def readwav(filename): # 打开WAV文档 f = wave.open(filename, "rb") # 读取格式信息 # (nchannels, sampwidth, framerate, nframes, comptype, compname) params = f.getparams() #print params nchannels, sampwidth, framerate, nframes = params[:4] # 读取波形数据 str_data = f.readframes(nframes) f.close() #将波形数据转换为数组 wave_data = np.fromstring(str_data, dtype=np.short) #将数组转换为m行n列的数组,-1为自动计算长度 wave_data.shape = -1, nchannels #print len(wave_data) #矩阵倒置 wave_data = wave_data.T #帧数×频率的倒数 time = np.arange(0, nframes) * (1.0 / framerate) # 绘制波形 pl.subplot(211) pl.plot(time, wave_data[0]) #第二声道 #pl.subplot(212) #pl.plot(time, wave_data[1], c="g") pl.xlabel("time (seconds)") pl.show() record("rectest.wav") readwav("rectest.wav")
时间: 2024-10-21 10:13:06