gTTS 直接输出 [英] gTTS direct output

查看:21
本文介绍了gTTS 直接输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以音频和文本形式进行聊天机器人的响应.

所有使用 gTTS 的示例代码似乎都需要将文本保存到文件中然后播放文件".

是否有其他方法可以简化流程,例如使用 gTTS 自动播放来自聊天机器人的响应"?

解决方案

如果你简单地看一下 文档,你会看到,在三个例子中,只有一个需要你调用save,第三个是专门称为直接播放声音".

所以,完全按照那个例子中的内容做,但是用你的字符串代替文字 'hello':

<预><代码>>>>从 gtts 导入 gTTS>>>从 io 导入 BytesIO>>>>>>my_variable = 'hello' # 你的真实代码是从聊天机器人那里得到的>>>>>>mp3_fp = BytesIO()>>>tts = gTTS(my_variable, 'en')>>>tts.write_to_fp(mp3_fp)

但请注意,gTTS 不附带 MP3 播放器;您需要一个单独的音频库来播放 mp3_fp 缓冲区:

<预><代码>>>># 将 `audio_fp` 作为 mp3 文件加载到>>># 您选择的音频库

正如文档所说,有很多这样的库,Stack Overflow 不是获得库推荐的好地方.我碰巧安装了一个库,名为 musicplayer,以及一个可以在此处轻松适应的示例应用程序,但从长远来看,它可能不是最简单的应用程序(它是为做更强大的低级内容而设计的):

<预><代码>>>>导入音乐播放器>>>课堂歌曲:... def __init__(self, f):... self.f = f... def readPacket(self, size):...返回 self.f.read(size)... def seekRaw(self, offset, wherece):... self.f.seek(offset, wherece)...返回 f.tell()>>>播放器 = 音乐播放器.createPlayer()>>>player.queue = [歌曲(mp3_fp)]>>>player.playing = 真

I want to make a chatbot's response in audio and text.

All the example code using gTTS seem like one needs to 'save the text into a file then play the file'.

Is there another way to simplify the process such as, play the 'response from chatbot' automatically, using gTTS?

解决方案

If you look even briefly at the docs, you'll see that, of the three examples, only one of them requires you to call save, and the third one is specifically called "Playing sound directly".

So, just do exactly what's in that example, but substitute your string in place of the literal 'hello':

>>> from gtts import gTTS
>>> from io import BytesIO
>>>
>>> my_variable = 'hello' # your real code gets this from the chatbot
>>> 
>>> mp3_fp = BytesIO()
>>> tts = gTTS(my_variable, 'en')
>>> tts.write_to_fp(mp3_fp)

But notice that gTTS doesn't come with an MP3 player; you need a separate audio library to play that mp3_fp buffer:

>>> # Load `audio_fp` as an mp3 file in
>>> # the audio library of your choice

As the docs say, there are many such libraries, and Stack Overflow is not a good place to get recommendations for libraries. I happen to have a library installed, named musicplayer, and a sample app that can be easily adapted here, but it's probably not the simplest one by a long shot (it's made for doing more powerful, low-level stuff):

>>> 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

这篇关于gTTS 直接输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆