#-*-coding:utf-8-*-ImportWaveImportPylab as PLImportNumPy as NP fromPyaudioImportpyaudio,paint16defrecord (filename):#Define of paramsNum_samples = 2000framerate= 16000Channels= 1Sampwidth= 2#Record TimeTime = 10defsave_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 ()defRecord_wave ():#Open the input of wavePA =Pyaudio () stream= Pa.open (format = paInt16, channels = 1,rate = framerate, input = True,frames_per_buffer =num_samples) Save_buffer=[]count=0 whileCount < Time*4:#read Num_samples sampling dataString_audio_data =Stream.read (num_samples) save_buffer.append (string_audio_data) Count+ = 1Print '.',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 ()defreadwav (filename):#Open a WAV documentf = wave.open (filename,"RB")#Read format information#(Nchannels, Sampwidth, framerate, Nframes, Comptype, Compname)params =F.getparams ()#Print paramsNchannels, Sampwidth, framerate, nframes = Params[:4]#Reading waveform DataStr_data =f.readframes (Nframes) f.close ()#convert waveform data to an arrayWave_data = np.fromstring (Str_data, dtype=np.short)#converts an array to an array of M row n columns, 1 for automatic length calculationWave_data.shape =-1, Nchannels#print len (wave_data)#Matrix inversionWave_data =Wave_data. T#number of frames x frequency reciprocalTime = Np.arange (0, nframes) * (1.0/framerate)#Drawing WaveformsPl.subplot (211) Pl.plot (time, wave_data[0])#Second channel#Pl.subplot (212)#Pl.plot (Time, wave_data[1], c= "G")Pl.xlabel ("Time (seconds)") pl.show () record ("Rectest.wav") Readwav ("Rectest.wav")
Read WAV file to draw waveform diagram