How to play audio from text withou saving it with gtts and Python

Опубликовано: 03 Октябрь 2024
на канале: John Starfire
9,208
61

Update: add time.sleep(5) at the end to hear the sound.
On python 3.11 it does not work still maybe for some issues with pygame that it is not still officially released for 3.11 (I am using the (pip install) pygame==2.1.3.dev8).
If you want to use gtts and python to save an mp3 audio created starting from a text is quite easy, but if you want to get the audio without saving anything, you need this code. It's quite simple, once you know how to do it, like for everything. Do not forget to subscribe.
Get the code here
https://pythonprogramming.altervista....

try it online
https://replit.com/@EducationalChan/s...

from gtts import gTTS
from io import BytesIO
import pygame
import time

def speak(text, language='en'):
mp3_fo = BytesIO()
tts = gTTS(text, lang=language)
tts.write_to_fp(mp3_fo)
return mp3_fo

pygame.init()
pygame.mixer.init()
sound.seek(0)
sound = speak("Python is cool always")
pygame.mixer.music.load(sound, 'mp3')
pygame.mixer.music.play()
time.sleep(5)

Alternatively you can do:
from gtts import gTTS

Create an instance of the gTTS class
tts = gTTS('Hello, world!')

Save the audio file as a temporary file
tts.save('hello.mp3', tempfile=True)

The temporary audio file will be deleted when the script finishes executing

This is the last post about this topic, with new cool stuffs
https://pythonprogramming.altervista....