We use Google's text-to-speech library gTTS to convert a text string into sound in the mp3 format (bytes buffer) and then play the sound using pygame.
First, install gTTS using
pip3 install gTTS
And then test using the following simple Python program.
from gtts import gTTS
from io import BytesIO
import pygame
pygame.mixer.init()
mp3_fp = BytesIO()
tts = gTTS('hello', 'en')
tts.write_to_fp(mp3_fp)
sound = BytesIO(mp3_fp.getvalue())
pygame.mixer.music.load(sound)
pygame.mixer.music.play()
Alternative Option
If gTTS is too slow (either because Google servers are slowed down or because the internet connection is spotty), one may consider using a program that runs locally on Pi.
Check out this website for further information.
First, make sure your Pi is configured to output the sound correctly:
sudo raspi-config
Select Advanced Options
Select the Audio option and pick a specific output you are planning to use (HDMI or Headphone jack).
Select <Ok> then <Finish> to get back to the command line.
Next, install festival
sudo apt-get install festival -y
And run a test:
os.system('echo "I find your lack of faith disturbing." | festival --tts')
Inside a Python code, we may use string interpolation
string = 'python is cool'
os.system(f'echo "{string}" | festival --tts')