Python--读取wav格式文件

来源:互联网 发布:淘宝950图片轮播代码 编辑:程序博客网 时间:2024/05/16 19:06
1、import wave 用于读写wav文件
它提供了一个方便的WAV格式接口。
但是不支持压缩/解压缩,支持单声道/立体声。
读取格式:
open(file[, mode])
如果file是一个字符串,那么就打开文件,不然就把它当做一个类文件对象。
mode是可以缺省的,如果输入的参数是一个类文件对象,那么file.mode将会作为mode的值。
mode可选参数如下:

'r', 'rb'

Read only mode.

'w', 'wb'

Write only mode.

注意不能同时完成读/写操作


2、wav文件读操作



3、numpy:shape改变数组形状


当某数轴的参数为-1时,根据元素个数,自动计算此轴的最大长度,入将c数组改成2行


4、实例代码

#!usr/bin/env python#coding=utf-8from Tkinter import *import waveimport matplotlib.pyplot as pltimport numpy as npdef read_wave_data(file_path):#open a wave file, and return a Wave_read objectf = wave.open(file_path,"rb")#read the wave's format infomation,and return a tupleparams = f.getparams()#get the infonchannels, sampwidth, framerate, nframes = params[:4]#Reads and returns nframes of audio, as a string of bytes. str_data = f.readframes(nframes)#close the streamf.close()#turn the wave's data to arraywave_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, 2#transpose the datawave_data = wave_data.T#calculate the time bartime = np.arange(0, nframes) * (1.0/framerate)return wave_data, timedef main():wave_data, time = read_wave_data("C:\Users\CJP\Desktop\miss_you.wav")#draw the waveplt.subplot(211)plt.plot(time, wave_data[0])plt.subplot(212)plt.plot(time, wave_data[1], c = "g")plt.show()if __name__ == "__main__":main()

5、效果