Reputation: 31
For my program I need to have a field of text spoken by Google's text to speech.
I found an API that manages to do it well (gTTS
, docs), however I really need to find a way to play the audio without saving it as a local file.
My code at the moment is this (I imported AudioSegment
from pydub
):
FileToPlay = io.BytesIO()
tts = gTTS(SecondText, lang = SecondLanguageVoice)
tts.write_to_fp(FileToPlay)
FileToPlay.read()
SoundToPlay = AudioSegment.from_mp3(io.BytesIO(FileToPlay))
play(SoundToPlay)
However, the variable type is not the expected one since the following error is brought:
TypeError: a bytes-like object is required, not '_io.BytesIO'
I've tried to see if I could someway convert my variable into a bytes-like object but I found nothing so far. Is there anything?
Upvotes: 3
Views: 1171
Reputation: 451
I don't have an answer to your question about converting into a bytes-like object. But doing a direct playback can be accomplished by using pyglet
I wrote the following lines so you can test it yourself!
from gtts import gTTS
from io import BytesIO
import pyglet
myMP3 = BytesIO()
tts = gTTS(text='Sound Check 1, 2, 3!', lang='en', slow=False)
tts.write_to_fp(myMP3)
myMP3.seek(0)
test = pyglet.media.load(None, file=myMP3, streaming=False)
test.play()
pyglet.app.run()
Upvotes: 2