Python 讀取wav格式檔案
阿新 • • 發佈:2018-12-26
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-8 from Tkinter import * import wave import matplotlib.pyplot as plt import numpy as np 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, 2 #transpose the data wave_data = wave_data.T #calculate the time bar time = np.arange(0, nframes) * (1.0/framerate) return wave_data, time def main(): wave_data, time = read_wave_data("C:\Users\CJP\Desktop\miss_you.wav") #draw the wave plt.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、效果