1, import wave used to read and write WAV files
It provides a convenient WAV format interface.
However, compression/decompression is not supported and mono/stereo is supported.
Read format:
Open (file[, mode])
If file is a string, open it or treat it as a class file object.
Mode can be default, and if the input parameter is a class file object, then File.mode will be the value of mode.
Mode optional parameters are as follows:
' R ', ' RB '
Read only mode.
' W ', ' WB '
Write only mode.
Note You cannot complete a read/write operation at the same time
2. wav file read Operation
3, Numpy:shape change array shape
when the parameter of a number axis is-1, the maximum length of the axis is calculated automatically according to the numbers of elements, and the C array is converted to 2 lines .
4. Instance Code
#!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, Nfra
Mes = 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 C oordinate) Wave_data.shape =-1, 2 #transpose the data Wave_data = Wave_data. T #calculate the time bar = 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, the effect