python学习之在文件夹中找到wav文件并读取

1.批量读取文件

import os
filepath="."
filenames=os.listdir(filepath)
for filename in filenames:
    print(filename)

输出结果:

表示路径用反斜杠/ ,右斜杠\为转义字符,一般引号前加r表示原始字符串,而不转义

常用获取帮助的方式包括:

help(str)
dir(str)
help(str.replace)

2.读取.wav文件

wave.open用法:

wave.open(file,mode)

mode可以是:'rb'读取文件;'wb'写入文件;没有同时支持读写的操作

wave_read_getparams的用法:

f = wave.open(file,'rb')
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]

其中,最后一行为常用的音频参数:

nchannels:声道数

sampwidth:量化位数(byte)

framerate:采样频率

nframe:总样本点数

以下是在文件中找到wav文件,并绘制波形图

import os
import wave
import numpy as np
import matplotlib.pyplot as plt

filepath="."
wavelist=[]
filenames=os.listdir(filepath)
for filename in filenames:
    name,category=os.path.splitext(filepath+filename)#分解文件扩展名
    if category=='.wav':  #若文件为wav音频文件
        wavelist.append(filename)
        
for wav in wavelist:        
    f=wave.open(wav,'rb')
    params=f.getparams()
    nchannels,sampwidth,framerate,nframes=params[:4]
    strData=f.readframes(nframes)
    f.close()
    waveData = np.fromstring(strData,dtype=np.int16)#将字符串转化为int
    waveData=waveData*1.0/max(abs(waveData))#幅值归一化
    
#plot the figure
    time=(1.0/framerate)*np.arange(0,nframes)
    plt.plot(time,waveData)
    plt.title('wave plot')
    plt.xlabel('Time')
    plt.ylabel('Amplitude')
    plt.grid('on')#标尺

猜你喜欢

转载自blog.csdn.net/Jum_Summer/article/details/89510856