我正在构建一个简单的 .wav audio 文件重命名器,它遍历每个文件并通过 playsound 模块播放它们,然后询问是否应该重命名文件。它可以正常播放每个文件,但是如果我继续使用重命名方法,则会收到“PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:”。或者,如果我省略 playsound 方法,它会迭代并让我 rename 每个文件都很好。
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...')```
回答1
我有一段时间没有查看该存储库了,但我相信它使用 c 类型调用 Windows 多媒体模块。当调用该模块时,您可以使用文件名或别名。最后我检查了一下, playsound 模块使用的是文件名而不是别名。因此,当 playsound 尝试打开具有相同文件名的新声音时,您会收到此错误。我遇到了很多问题,尤其是跨平台的模块,所以我分叉了我自己的,做了一堆名为preferredsoundplayer的修改。我喜欢 playsound 模块,但是在我的情况下实现它时我遇到了需要解决的问题,所以我尽我所能制作一个适用于我的项目的替代品。
它使用别名并包含我编写的手动垃圾收集,以确保关闭声音实例。它还具有停止声音和循环等额外功能。如果此替换模块不起作用,请告诉我。
https://pypi.org/project/preferredsoundplayer/
您可以尝试 pip install preferredsoundplayer
安装然后 from preferredsoundplayer import *
或只是 from preferredsoundplayer import playsound
我认为这会解决问题。如果这不能解决您的问题,请发表评论。