读取wav文件绘制波形图 发表于 2019-01-02 分类于 Python 本文字数: 1.6k 阅读时长 ≈ 1 分钟 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# -*- coding: utf-8 -*-import waveimport pylab as plimport numpy as npfrom pyaudio import PyAudio,paInt16def record(filename):#define of paramsNUM_SAMPLES = 2000framerate = 16000channels = 1sampwidth = 2#record timeTIME = 10def 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 wavepa = PyAudio()stream = pa.open(format = paInt16, channels = 1,rate = framerate, input = True,frames_per_buffer = NUM_SAMPLES)save_buffer = []count = 0while count < 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()def readwav(filename):# 打开WAV文档f = wave.open(filename, "rb")# 读取格式信息# (nchannels, sampwidth, framerate, nframes, comptype, compname)params = f.getparams()#print paramsnchannels, 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")