在python中重新打开声音文件时出错 [英] Error while re-opening sound file in python
问题描述
我正在编写一个程序,该程序只是重复您输入的任何文本,并且在我第一次测试它时似乎可以正常工作.问题是我第二次尝试键入任何内容时都会崩溃,并说我对其录音的声音文件的权限被拒绝.我相信是因为该文件已经打开,但是我仍然不知道如何解决它.我正在使用gTTS和Pygame模块.
I was in the process of making a program that simply repeats any text you enter, and seemed to be working when I first tested it. The problem is that the second time I attempt to type anything, it crashes and says that permission was denied to the sound file I was recording it to. I believe it is because the file was already opened, but none the less I do not know how to fix it. I am using the gTTS and Pygame modules.
from gtts import gTTS
from tempfile import TemporaryFile
from pygame import mixer
#Plays Sound
def play():
mixer.init()
mixer.music.load("Speech.mp3")
mixer.music.play()
#Voice
def voice(x):
text = gTTS(text= x, lang= 'en')
with open("Speech.mp3", 'wb') as f:
text.write_to_fp(f)
f.close()
play()
#Prompts user to enter text for speech
while True:
voice_input = input("What should Wellington Say: ")
voice(voice_input)
推荐答案
弄清楚了.我添加了此功能:
Figured it out. I added this function:
def delete():
sleep(2)
mixer.music.load("Holder.mp3")
os.remove("Speech.mp3")
并在.play()
之后调用它,因此它现在只需在完成后删除该文件,然后在下次需要使用它时重新创建它即可.
And call it after .play()
, so it now simply deletes the file when it is done and then re-creates it when you need to use it next.
这篇关于在python中重新打开声音文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!