'Can't rename .wav file after playsound. WinError 32, file in use
I am building a simple .wav audio file renamer that iterates over each file and plays them via playsound module before asking if the file should be renamed. It plays each file just fine, but I get "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: " if I continue to the renaming method. Alternatively, if I leave out the playsound method it iterates and lets me rename each file just fine.
def sample_rename(self, sample):
new_sample_name = input('Rename Sample: ').title()
new_name = new_sample_name + '.wav'
os.rename(os.path.join(self.filepath, sample), os.path.join(self.filepath, new_name))
print(f'Sample renamed {new_name}')
return sample
def play_sound(self, sample):
playsound(self.filepath + '/' + sample)
return
def sample_player(self): #WinError 32 (file is being used), 'with open' somewhere?
repr(self.filepath)
samples = os.listdir(self.filepath)
for sample in samples:
print(sample)
self.play_sound(sample)
name_check = input("Do you need to rename this sample? Y/N ").lower()
if name_check == 'y':
self.sample_rename(sample)
print(f'End of samples...')```
Solution 1:[1]
I haven't looked at that repository for a while, but I believe it uses c-type calls to a windows multimedia module. When calls are made to that module, you can use a filename or an aliases. Last I checked, the playsound module was using a filename instead of an alias. So when playsound trys to open a new sound with the same filename you get this error. I had a lot of issues especially cross platform with the module so i forked my own an made a bunch of modifications called preferredsoundplayer. I like the playsound module but I had issues that needed fixed while implementing it in my situation so I did my best to make a substitute that would work for my projects.
It uses aliases and contains manual garbage collection I wrote to make sure sound instances are closed. It also has extra features like stopping sound and looping etc. If this substitution module does not work please let me know.
https://pypi.org/project/preferredsoundplayer/
You can try
pip install preferredsoundplayer to install and then from preferredsoundplayer import * or just from preferredsoundplayer import playsound and I think this will take care of the problem. Please comment if this does not solve your problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | garydavenport73 |
