简体   繁体   English

尝试遍历目录中的 .wav 文件(Python)

[英]Trying to iterate through .wav files in a directory (Python)

I'm trying to iterate through a directory that contains a list of wav files as shown below:我正在尝试遍历包含 wav 文件列表的目录,如下所示:

在此处输入图像描述

My goal is to go through each wav file and add it to a wav file called transcript.wav which is located inside its parent directory.我的目标是通过每个 wav 文件 go 并将其添加到位于其父目录内的名为 transcript.wav 的 wav 文件中。

For example, the output I'm hoping to get is that for every chunk there is a corresponding "new_audio" file with the correct number.例如,我希望得到的 output 是每个块都有一个具有正确编号的相应“new_audio”文件。 So "chunk0.wav" becomes "new_audio0.wav" , "chunk1.wav" becomes "new_audio1.wav" and so on.所以"chunk0.wav"变成"new_audio0.wav""chunk1.wav"变成"new_audio1.wav"等等。

Here is my code:这是我的代码:

import os
from pydub import AudioSegment

directory = "C:/Users/Nahuel/Workfiles/audio_chunks"

for file in sorted(os.listdir(directory)):
    filename = os.fsdecode(file)
    if filename.endswith(".wav"):
        p1 = AudioSegment.from_wav(filename)
        p2 = AudioSegment.from_wav("C:/Users/Nahuel/Workfiles/transcript.wav")
        newAudio = p1 + p2
        newAudio.export('new_audio.wav', format="wav")
        continue
    else:
        continue

This is the error I get.这是我得到的错误 It says that file 'chunk0.wav' is not found.它说找不到文件“chunk0.wav”。 But it is there in the directory so I am left scratching my head.但它在目录中,所以我只能摸不着头脑。

在此处输入图像描述

Any help would be greatly appreciated.任何帮助将不胜感激。 Thank you for your help.谢谢您的帮助。

It seems that you're just not running your code in the wav directory.看来您只是没有在 wav 目录中运行代码。 listdir just return the filename, not the whole path, you need to join with the directory listdir只返回文件名,而不是整个路径,你需要加入目录

p1 = AudioSegment.from_wav(os.path.join(directory, filename))

You may need to use an absolute path for your filename , depending on where your Python program is stored.您可能需要使用绝对路径作为filename ,具体取决于 Python 程序的存储位置。 You should use:你应该使用:

filename = os.path.join(directory, file)

instead of:代替:

filename = os.fsdecode(file)

Side note, check your indentation in the for loop.旁注,检查 for 循环中的缩进。

You can use the glob package and os.path.join() to help.您可以使用glob package 和os.path.join()来提供帮助。 This code removes some of those checks for .wav files as well because you can explicitly search for those using the glob.glob() function.此代码还删除了对.wav文件的一些检查,因为您可以使用glob.glob() function 显式搜索这些检查。

import os
import glob
from pydub import AudioSegment

directory = os.path.join('c:/', 'Users', 'Nahuel', 'Workfiles')

for file in sorted(glob.glob(os.path.join(directory, 'audio_chunks', '*.wav'))):
    p1 = AudioSegment.from_wav(file)
    p2 = AudioSegment.from_wav(os.path.join(directory, 'transcript.wav')
    newAudio = p1 + p2
    newAudio.export('new_audio.wav', format="wav")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM