0

I know that the question has often been asked but I can not solve the problem in my case:

I created a script that looks at a folder where I stocked audio file (.wav). All audio file that have more than 10 seconds duration a moved into another folder, the other are 0 padded to have only 10 secondes audio files:

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(os.path.join(path_to_sound, 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')

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'

Only Python with Jupyter Notebook is running. I guess that I need to close the file before I copy it. The problem is that i'm using file as str object, then i cant use close()

QQ1821
  • 55
  • 5

1 Answers1

0

https://stackoverflow.com/a/27215504/10850556

this solution might work

If this answer hasn't resolved, you can go back.

Ali Gökkaya
  • 11
  • 1
  • 6
  • Thx, I tried to apply the solution in my context but is doenst work, since i'm new to python, my syntaxe is probably wrong, what kind of module I have to use before `.open(myfilepath)` in my case? – QQ1821 Mar 25 '21 at 14:42
  • It would have to be the `AudioSegment` object that has the file open, right? If it did, then I'd think you'd need to do something like `audio.close()`. But there is no such method on the object, and googing around, it doesn't seem that this object opens files, or at least doesn't keep them open. If it is your code that has the file open, then you need to figure out what to do in your code to close the file via whatever reference you can get to the object that has the file open. Trying to close a file using just its path makes no sense. It's a total hack. The opener should close the file. – CryptoFool Mar 25 '21 at 16:10
  • Do you only have .wav in your file? – Ali Gökkaya Mar 25 '21 at 19:54
  • https://stackoverflow.com/questions/2060628/reading-wav-files-in-python This resource can be useful, my friend – Ali Gökkaya Mar 25 '21 at 19:56
  • Well, I made a mistake in my code, I replaced `if pad_ms > len(audio):` by `if pad_ms < len(audio):` and I got no error now. Even if i dont get the link with my last error, anyway, thx @CryptoFool and @AliGökkaya, you have invested and thats really helped me – QQ1821 Mar 26 '21 at 08:39