pythonwavaudiosegment

Error trying to use AudioSegment for .wav files


I'm trying to iterate through all the .wav files in a folder "audios", but I receive the following error. I found similar questions that were solved by installing ffmpeg, but that didn't help.

    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-24-29ba732186ac> in <module>
          1 for audio_file in os.listdir(base_path+"audios"):
          2     # read wav audio file
    ----> 3     audio = AudioSegment.from_wav(audio_file)
          4 
          5     # pass audio file, start time, end time & chunk path to create chunk
    
    ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pydub\audio_segment.py in from_wav(cls, file, parameters)
        806     @classmethod
        807     def from_wav(cls, file, parameters=None):
    --> 808         return cls.from_file(file, 'wav', parameters=parameters)
        809 
        810     @classmethod
    
    ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pydub\audio_segment.py in from_file(cls, file, format, codec, parameters, start_second, duration, **kwargs)
        649         except TypeError:
        650             filename = None
    --> 651         file, close_file = _fd_or_path_or_tempfile(file, 'rb', tempfile=False)
        652 
        653         if format:
    
    ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pydub\utils.py in _fd_or_path_or_tempfile(fd, mode, tempfile)
         58 
         59     if isinstance(fd, basestring):
    ---> 60         fd = open(fd, mode=mode)
         61         close_fd = True
         62 

FileNotFoundError: [Errno 2] No such file or directory: 'name_of_file.wav'

Solution

  • os.listdir doesn't return the full paths of files in the directory you give it, just the names they have within that directory. You will need to prepend this directory name to the filename you pass to AudioSegment.from_wav.

    Try replacing the line

         audio = AudioSegment.from_wav(audio_file)
    

    with

         audio = AudioSegment.from_wav(os.path.join(base_path+"audios", audio_file))