如何读取文件夹和子文件夹*.wav;以及输入训练模型的特征提取?

2024-09-27 21:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个主文件夹,其中包含20个子文件夹。任何子文件夹都有6个子文件夹(20个扬声器,任何扬声器的声音(*.wav)分类为6类)。你知道吗

我想阅读所有的*.wav文件和特征提取。特征提取是我的神经网络训练模型的输入。你知道吗

如何读取和提取所有.wav文件的特征?你知道吗

所有的课程必须一起训练?怎样?你知道吗

从主文件夹读取wav文件的代码如下(但此代码仅读取一个子文件夹):

import os
import scipy.io.wavfile as wav

r_dir = '/my path/'

data = []
rate = []
for root,sub,files in os.walk(r_dir):
    files = sorted(files)
    for f in files:
        s_rate, x = wav.read(os.path.join(root, f))
        rate.append(s_rate)
        data.append(x)

对于特征提取,我使用以下代码(我希望对所有子文件夹和wav文件进行特征提取):

from python_speech_features import fbank
import scipy.io.wavfile as wav

(rate,sig)=wav.read("/my path for one .wav file")
fbank_feat = fbank(sig,rate)

print(fbank_feat)

我很困惑。请帮助我怎么做,一步一步。你知道吗

谢谢。你知道吗


Tags: 文件path代码ioimport文件夹forrate
2条回答

要读取目录和子目录中的所有*.wav文件,可以使用以下命令:

#Read all *.wav files inside dir & sub dir
import xlrd
import os
import scipy.io.wavfile as wav

mydir = (os.getcwd()).replace('\\','/') + '/'

#Get all *wav files include subdir
filelist=[]
for path, subdirs, files in os.walk(mydir):
    for file in files:
        if (file.endswith('.wav') or file.endswith('.WAV')):
            filelist.append(os.path.join(path, file))
number_of_files=len(filelist)
print(filelist)

wav_data=[]
for i in range(number_of_files):
    #extract all *.wav files here
    samplerate, data = wav.read(filelist[i])
    wav_data.append(data)
print(wav_data)

我的目录:

输出:

['D:/SOF/answer30/file_example_WAV_5MG.wav', 'D:/SOF/answer30/subdir1\\file_example_WAV_1MG.wav', 'D:/SOF/answer30/subdir2\\file_example_WAV_2MG.wav']

WAV数据:

[array([[-204,   23],
       [-232,   32],
       [-192,   34],
       ...,
       [4938, 4256],
       [4974, 3977],
       [4734, 3798]], dtype=int16), array([[ -114,    23],
       [ -241,     3],
       [ -285,   -29],
       ...,
       [ -772, -1059],
       [ -422,  -840],
       [ -787,  -314]], dtype=int16), array([[ -139,    18],
       [ -215,    34],
       [ -196,     6],
       ...,
       [ -523,  -563],
       [ -765,  -319],
       [-1002,  -190]], dtype=int16)]

globpathlib.Path一起使用时更好。你知道吗

from pathlib import Path

path = Path('D:\\test path').glob('**/*.wav')
wavs = [str(wavf) for wavf in path if wavf.is_file()]

print(wavs)

收益率

D:\test path\a..wav
D:\test path\b.wav
D:\test path\sub 1\1a..wav
D:\test path\sub 1\1b.wav
D:\test path\sub 1\nest a\aaa..wav
D:\test path\sub 1\nest a\bbb.wav
D:\test path\sub 2\2a..wav
D:\test path\sub 2\2b.wav

相关问题 更多 >

    热门问题