Text-to-Speech
Text-to-Speech (TTS) is the most widely used form of AI audio generation. It converts written text into spoken audio and is available through many free and paid services.
How Text-to-Speech Works
Modern neural text-to-speech systems work in two stages:
- 1Text analysis: the system analyzes the text to understand sentence structure, which words to emphasize, and where to pause. It also handles abbreviations, numbers, and special characters.
- 2Audio synthesis: the system generates a waveform (the actual audio signal) that matches the analyzed text, using a voice model it learned from real human speech recordings.
The result sounds natural because the model learned the subtle patterns of human speech: how pitch changes at the end of a question, how speakers pause after a comma, how emphasis changes word meaning.
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
Try Text-to-Speech with Python
# Using a simple Python text-to-speech library
# Run: pip install pyttsx3
import pyttsx3
def text_to_speech_demo():
"""
A simple text-to-speech demo using the built-in pyttsx3 library.
This works offline and does not require an API key.
"""
# Initialize the text-to-speech engine
engine = pyttsx3.init()
# Get available voices
voices = engine.getProperty('voices')
print(f"Available voices: {len(voices)}")
for i, voice in enumerate(voices[:3]): # Show first 3
print(f" Voice {i}: {voice.name}")
# Set voice properties
engine.setProperty('rate', 150) # Speed: words per minute (150 is normal)
engine.setProperty('volume', 0.9) # Volume: 0.0 to 1.0
# Text to convert to speech
text = """
Welcome to the Generative AI course on PriyGop.
In this module, we are learning about AI audio generation.
Text-to-speech technology converts written text into spoken audio.
"""
print()
print("Converting text to speech...")
print(f"Text: {text.strip()[:80]}...")
# Convert text to speech (plays audio)
engine.say(text)
engine.runAndWait()
# Optionally save to a file
# engine.save_to_file(text, 'output.mp3')
# engine.runAndWait()
print("Speech complete.")
# Note: pyttsx3 uses your system's built-in TTS
# For higher quality, use cloud APIs like ElevenLabs or OpenAI TTS
text_to_speech_demo()Tip
Tip
For production-quality AI voice, use cloud-based APIs like ElevenLabs or OpenAI's TTS API. They produce far more natural voices than offline libraries. Always store your API key in an environment variable and never hardcode it in your source code. You will learn how to use AI APIs securely in Module 8.