Search code examples
pythonloopsoperating-systemwavpydub

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:

enter image description here

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.

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. So "chunk0.wav" becomes "new_audio0.wav", "chunk1.wav" becomes "new_audio1.wav" and so on.

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. But it is there in the directory so I am left scratching my head.

enter image description here

Any help would be greatly appreciated. Thank you for your help.


Solution

  • It seems that you're just not running your code in the wav directory. listdir just return the filename, not the whole path, you need to join with the directory

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