问题描述
# Save directory path in 'path'
path = r'---path '
# Declare a dummy Numpy array (row vector)
result_array = np.empty([1,54])
# Create a list of audio file names 'file_list'
file_list = os.listdir(path)
i=0
for filename in file_list:
# Read WAV file. 'rosa.core.load' returns sampling frequency in 'fs' and audio signal in 'sig'
sig,fs = rosa.core.load(path + '\\' + file_list[i],sr=None)
# Calculate the average mfcc (utterance-level features) using 'rosa.feat.mfcc()' and 'np.mean' method. '.T' transposes the rows and columns. 'axis=0' indicates average is calculated column-wise
avg_mfcc_feat = np.mean(rosa.feature.mfcc(y=sig,sr=fs,n_mfcc=26).T,axis=0)
# Calculate the standard deviation of mfcc (utterance-level features) using 'rosa.feat.mfcc()' and 'np.std' method. '.T' transposes the rows and columns. 'axis=0' indicates average is calculated column-wise
std_mfcc_feat = np.std(rosa.feature.mfcc(y=sig,axis=0)
# Calculate the average zero crossing rate (utterance-level feature) using 'rosa.feat.zero_crossing_rate()' and 'np.mean' method. '.T' transposes the rows and columns. 'axis=0' indicates average is calculated column-wise
zcross_feat = rosa.feature.zero_crossing_rate(sig)
avg_zcross_feat = np.mean(rosa.feature.zero_crossing_rate(y=sig).T,axis=0)
# Append the three 1D arrays into a single 1D array called 'feat'.
feat0 = np.append(avg_mfcc_feat,std_mfcc_feat,axis=0)
feat1 = np.append(feat0,avg_zcross_feat,axis=0)
# Save emotion label from file name. 'path' contains directory's address,'file_list' contains file name,and '\\' joins the two to form file's address
label = os.path.splitext(os.path.basename(path + '\\' + file_list[i]))[0].split('-')[2]
# Create a new Numpy array 'sample' to store features along with label
sample = np.insert(feat1,obj=53,values=label)
result_array = np.append(result_array,sample)
i+=1
# Print out the 1D Numpy array
result_array
我在尝试读取内容并遍历 Ravdess 数据集的子目录时遇到此错误。有人能告诉我我做错了什么吗?任何帮助深表感谢。谢谢!
解决方法
1. os.listdir()
列出目录的条目,即它包含的文件和目录。如果要递归包含 path
下的所有文件和文件夹,请使用 os.walk()
。
要仅使用来自 os.listdir()
的文件,请添加带有 os.path.isfile()
的检查:
如果 path 是一个 existing
常规文件,则返回 True
。这遵循符号链接,因此对于同一路径,islink()
和 isfile()
都可以为真。
for filename in file_list:
if not os.path.isfile(os.path.join(path,filename)):
# not a file,skip it
continue
# rest of your code here
sig,fs = rosa.core.load(...)
...
2. 在 for
循环内,您有两种情况在其中放置了 path + '\\' + file_list[i]
- 这应该只是 path + '\\' + filename
,或者更好os.path.join(path,filename)
。
- 如果您需要文件名迭代的索引,请执行
for i,filename in enumerate(file_list):
而不是手动递增i
。 - 而不是多次重复
os.path.join(path,filename)
,而是在循环开始时将其放入一个变量中:for filename in file_list: filepath = os.path.join(path,filename) if not os.path.isfile(filepath): continue sig,fs = rosa.core.load(filepath,sr=None) ...