如何使用SOX使用python脚本高效地将大量.wav文件的采样率降至8KHz

2024-04-27 14:36:46 发布

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

我有一个名为wav的目录,其中包含更多的目录(目录名如022023,…999,asr_bangla_0)。wav目录包含252000个.wav音频文件,分散在这些子目录中

我想用带有python脚本的sox对它们进行详细的示例。我尝试过os.listdir(),但它会占用全部CPU内存和RAM(8GB),并且无法转换。有人能建议我如何优化代码吗

我尝试过os.listdir(),可能是因为加载了所有数据而变慢了。这是我的python脚本,我使用cmd从wav目录运行它

'''
Run this python file from sourceDir.
structure of sourceDir
wav--
     |-->022
     |-->023
     |-->999
     |-->...
     |-->asr_bangla_0
     |-->this python script
'''
import os
soxExeDirectoryPath = "E:\\iOS\\sox142\\" # exe for sox software
desPath = "C:\\sphinx\\other\\wav3" # where to save the converted audio
sourceDir = "C:\\sphinx\\other\\wav\\" # orginal audio

for dirc in os.listdir():
    # print(dirc)
    childDir = sourceDir + dirc
    print(childDir + "----------------------------------------")
    if os.path.isdir(childDir):
        os.chdir(childDir)
        f_list = os.listdir()
        for audioFile in f_list:
            # print("*" + audioFile + "*")
            if audioFile.endswith(".wav"):
                convert8KHzCommand = soxExeDirectoryPath + "sox " + audioFile + " -r 8000 " + desPath + '\\' + dirc + '\\' + audioFile
                print(convert8KHzCommand)
                os.popen(convert8KHzCommand)

我希望通过运行脚本转换所有文件,但无法使用listdir()进行转换


Tags: 目录脚本forosasrlistdirprintwav