我有一个函数text_to_speach
,它接收文本并与gtts
模块对话:
def text_to_speach(text):
try:
tts = gTTS(text=text, lang='fr', tld="com", slow=False)
tts.save("audio.mp3")
playsound.playsound('audio.mp3', False)
os.remove('audio.mp3')
except:
print('Check Speak issue !!!')
该函数在线程内部运行:
def speak(reply):
thread = Thread(target=text_to_speach, args=(reply,), daemon=True)
thread.start()
现在,每次运行speak()
函数时,它都会创建一个Thread
我不希望它创建多个线程。
因此,我希望每次运行speak
函数时,线程都会在那之后结束。
示例:
speak("some text")
#Thread end
speak("some text 2")
#Thread end
speak("some text 3")
#Thread end
所以我的问题是如何结束线程?
阻塞解决方案:
def speak(reply):
thread = Thread(target=text_to_speach, args=(reply,), daemon = True)
thread.start()
thread.join() # it will block till thread ends