python wave文件的额处理方法

来源:互联网 发布:淘宝购物付款流程图 编辑:程序博客网 时间:2024/05/21 17:16
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import wave


'''
    This is a wave test program 
'''



def read_wave_data(file_path):  
    #open a wave file, and return a Wave_read object  
    f = wave.open(file_path,"rb")  
    #read the wave's format infomation,and return a tuple  
    params = f.getparams()  
    #get the info  
    nchannels, sampwidth, framerate, nframes = params[:4]  
    #Reads and returns nframes of audio, as a string of bytes.   
    str_data = f.readframes(nframes)  
    #close the stream  
    f.close()  
    #turn the wave's data to array  
    wave_data = np.fromstring(str_data, dtype = np.short)  
    #for the data is stereo,and format is LRLRLR...  
    #shape the array to n*2(-1 means fit the y coordinate)  
    wave_data.shape = -1, nchannels  
    #transpose the data  
    wave_data = wave_data.T  
    #calculate the time bar  
    time = np.arange(0, nframes) * (1.0/framerate)  
    return wave_data, nchannels,sampwidth,framerate 


def write_wave_data(file_path, wave_data, nchannels, sampwidth,framerate):
    f = wave.open(file_path,"wb")
    f.setnchannels(nchannels)
    f.setsampwidth(sampwidth)
    f.setframerate(framerate)
    f.writeframes(wave_data.tostring())
    return


if __name__ == "__main__":
    wave_data,nchannels,sampwidth,framerate = read_wave_data("voice_tv_door_binaural.wav")
    print nchannels,sampwidth,framerate
    print wave_data
    print type(wave_data)
    
print "OK"
0 0