-1

I am running into an issue when trying to extract mono audio from a stereo file using pydub.

Here is the code:

import wave
import audioop
from pydub import AudioSegment

def cantDeleteLockedFile():

    audiofile = "/Volumes/test/stereotest.wav"
    audiostrip = AudioFileClip(audiofile)

    if audiostrip.nchannels > 1:
        with open(audiofile, "rb") as oaudiofile:
            mono_audios = AudioSegment.from_file(oaudiofile, format="wav")

            # List of AudioSegments, mono files, which can be accessed via [0] and [1]
            mono_audios = mono_audios.split_to_mono()
            audioChannelOne = str(audiofile.rsplit(".", 1)[0]) + "a.wav"

             # This line is locking the stereo file
             mono_left = mono_audios[0].export(audioChannelOne, format="wav")
             # This extracts the mono left track from the stereo track
             # On the same location a file will be created, in this example:
             # "/Volumes/test/stereotesta.wav"

            # This should unlock the file, but doesnt
            mono_left.close()
         
            # When trying to delete the file here, it will fail 
            # without exception raised
            os.remove(audiofile)

           if os.path.exists(audiofile):
              return True

           else:
              return False

  return False

After executing this code, which in my case is embedded into an API microservice system, that does not exit the code. Then the stereo audio file will be locked, for as long as that micro service is running. The file will not be deleted and function return value will be "False". If you later manually on the filesystem navigate to that file and try to delete it manually, it will also fail. It will first delete it, but then it will magically pop back up.

I am aware of this issue being discussed on other boards before. However the proposed solution does not work.

ref: https://github.com/jiaaro/pydub/issues/305

Either I am missing something completely. However, perhaps there is a workaround to forcibly unlock a file, so it can be deleted? I did not find a reference online. Basically I know, that pydub is locking the resource, I can't get it to unlock the wav file behind the Audio Segment.

Happy to read your feedback and suggestions.

Thank you!

DeltaFi
  • 55
  • 4

1 Answers1

0

The Audiosegment used to check for stereo files also needs to be closed. This was blocking the file on the storage side.

Adding a simple:

audiostrip.close()

solved the problem.

DeltaFi
  • 55
  • 4