您的位置:首页 > 编程语言 > Python开发

python wave文件的额处理方法

2016-06-05 19:35 816 查看
#!/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"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python