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、效果