0

I'm preprocessing datas to apply deep learning on audio files. I have a directory of audio file (.wav) with differents length and my goal is to use 0 padding in order to have only 10 secondes files duration. I also want to move move files that are longer than 10 secondes in an other directory:

from pydub import AudioSegment
import os
import  shutil

path_to_sound = r'my\path\to\sound'
path_to_export = r'my\path\to\export'
path_for_too_long  = r'my\path\to\other_directory'

pad_ms= 10000
file_names=os.listdir(path_to_sound)

print(file_names) # ['30368.wav', '41348.wav', '42900.wav', '42901.wav', '42902.wav']


for name in file_names:
    audio= AudioSegment.from_wav(os.path.join(path_to_sound, name))
     
    if pad_ms > len(audio):
        shutil.move(name,path_for_too_long )
    else:    
        silence = AudioSegment.silent(duration=pad_ms-len(audio)+1)
    
        padded = audio + silence
        padded.export(os.path.join(path_to_export, name), format = 'wav')

When running this I got the following errors:

FileNotFoundError: [WinError 2] The specified file can not be found : '41348.wav' -> 'C:\\Users\\path_for_too_long\\41348.wav'
...
FileNotFoundError: [Errno 2] No such file or directory: '41348.wav'

I think the error is due to the way i'm using shutil.move()

QQ1821
  • 143
  • 9

2 Answers2

0

before u delete,try to findout if is exist.

import os
path = ''
if os.path.exists(path):
    func_to_delete()
pepper
  • 353
  • 1
  • 7
  • thx, but the error specify that the file does not exist in the destination directory, which is normal because he is empty and I want to move files in – QQ1821 Mar 25 '21 at 10:14
0

shutil.move expects the full path, here you are providing the name which corresponds to the filename and not the file path.

You have to update the line:

shutil.move(name, path_for_too_long)

to:

shutil.move(os.path.join(path_to_sound, name), path_for_too_long)

Remark: if you are using Python 3.4+ you can use pathlib instead of os to handle paths. You can find 2 articles on this:

  • Thx, it really help me – QQ1821 Mar 25 '21 at 11:54
  • Some files are moving but I got the following error `PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\path_to_sound"\\filename.wav'`, how am i supposed to close the file? – QQ1821 Mar 25 '21 at 13:09
  • Hard to say what is the cause of this error, did you launch several runs at the same time? – M. Perier--Dulhoste Mar 25 '21 at 15:31
  • No only python with Jupyter Notebook is running. According to this [link](https://stackoverflow.com/questions/27215462/permissionerror-winerror-32-the-process-cannot-access-the-file-because-it-is/27215504#27215504) I think I understood that the probleme came from the opining of the file, but I have no idea how to apply this in my case – QQ1821 Mar 25 '21 at 15:37