如果您只是简单地看一下docs,您会发现在三个示例中,只有其中一个需要您调用
save,第三个示例专门称为“直接播放声音”。
因此,只需执行该示例中的操作,但用字符串代替文字即可
'hello':
>>> from gtts import gTTS>>> from io import BytesIO>>>>>> my_variable = 'hello' # your real pre gets this from the chatbot>>> >>> mp3_fp = BytesIO()>>> tts = gTTS(my_variable, 'en')>>> tts.write_to_fp(mp3_fp)
但是请注意,gTTS并未配备MP3播放器;您需要一个单独的音频库来播放该
mp3_fp缓冲区:
>>> # Load `audio_fp` as an mp3 file in>>> # the audio library of your choice
正如文档所说,有许多这样的库,而Stack
Overflow并不是获取库建议的好地方。我碰巧安装了一个名为的库
musicplayer,并提供了一个示例应用程序,可以在此处轻松进行修改,但是从长远来看,它可能不是最简单的一个(它是为执行更强大的低级任务而设计的):
>>> import musicplayer>>> class Song:... def __init__(self, f):... self.f = f... def readPacket(self, size):... return self.f.read(size)... def seekRaw(self, offset, whence):... self.f.seek(offset, whence)... return f.tell()>>> player = musicplayer.createPlayer()>>> player.queue = [Song(mp3_fp)]>>> player.playing = True



