DEV Community

Cover image for Text-To-Speech in Python
Carmen
Carmen

Posted on

Text-To-Speech in Python

Introduction

I’ve been working in the development of Python software that aimed to enable playing chess directly from the terminal. Initially, the project was conceive as a platform for local matches between players or against a bot, as well as online games.

In addition to its primary functionality, the project’s focus has shifted towards becoming an accessible tool for people with functional diversity, implying the integration of assistive technologies such as Text-To-Speech to ensure an inclusive experience.

In this regard, I have dedicated time to researching the available options in Python for implementing text-to-speech for free.

Library Installation

Firstly, it’s crucial to consider the libraries that will allow us to incorporate Text-To-Speech into our software. Among these libraries, we will be using:

  • Google Text-to-Speech (gTTS): Used for generating audio files from the provided text.
  • Pygame: Used for playing the generated audio without concerns regarding device compatibility or operating systems.

Code

from gtts import gTTS
import pygame

# Initialize Pygame mixer
pygame.mixer.init()

# Path to the audio file
sound_file = "sound_file.mp3"

# Generate audio from text
text_to_speech = gTTS(text='Hi, good evening', lang='en')
tts.save(sound_file)

# Load the audio file into Pygame
sound = pygame.mixer.Sound(sound_file)

# Play the audio
sound.play()

# Wait for the sound to finish playing
while pygame.mixer.get_busy(): 
    pygame.time.delay(100)
Enter fullscreen mode Exit fullscreen mode

This simple code demonstrates how to use the gTTS library to convert specific text, in this case, “Hi, good evening”, into an audio file in MP3 format. Subsequently, using Pygame, we play the audio file.

Top comments (0)