Nahuel Mel
Nahuel Mel

Reputation: 61

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.

Upvotes: 1

Views: 1928

Answers (3)

Eric Leung
Eric Leung

Reputation: 2604

You can use the glob package and os.path.join() to help. This code removes some of those checks for .wav files as well because you can explicitly search for those using the 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")

Upvotes: 0

Anis R.
Anis R.

Reputation: 6922

You may need to use an absolute path for your filename, depending on where your Python program is stored. You should use:

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

instead of:

filename = os.fsdecode(file)

Side note, check your indentation in the for loop.

Upvotes: 0

azro
azro

Reputation: 54168

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))

Upvotes: 3

Related Questions