您如何直接在python中播放声音?

时间:2019-10-31 17:49:52

标签: python audio temporary-files playsound gtts

我正在尝试找到一种在python中播放声音而不下载任何声音文件的最佳方法(例如,将临时文件与tempfile一起使用)。这是针对使用speak的{​​{1}}函数的;我已经想出了一种将语音文件保存到gTTS对象的解决方案。我遇到的麻烦就是尝试播放。

NamedTemporaryFile

在这里我只需要替换from gtts import gTTS from tempfile import TemporaryFile def speak(text, lang = 'en'): gTTS(text = text, lang = lang).write_to_fp(voice := TemporaryFile()) #Play voice voice.close() ,这是我尝试的解决方案:

#Play voice

这将返回错误: from gtts import gTTS from tempfile import NamedTemporaryFile from playsound import playsound def speak(text, lang = 'en'): gTTS(text = text, lang = lang).write_to_fp(voice := NamedTemporaryFile()) playsound(voice.name) voice.close() 注意:该解决方案无需使用上述gTS以外的任何模块。只要The specified device is not open or is not recognized by MCI.函数可以重复使用且不保存任何文件,就足够了。

1 个答案:

答案 0 :(得分:1)

您应该使用pyttsx3而不是gtts。无需保存语音剪辑,因为语音将在运行时直接播放。您可以在此处找到详细信息:https://pypi.org/project/pyttsx3/

import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()