Implementing Text To Speech / Audio with Python3 and pyttsx3

CK CK 3788 
Created at
Updated at  
358 0 0

pyttsx3 is a Python library that allows you to convert text into speech. It is a simple and easy-to-use library, making it ideal for projects requiring speech synthesis. Pyttsx3 works by leveraging various speech engines available on your system, such as the built-in Windows speech engine or the open-source eSpeak engine. This makes it a versatile tool for developers who need to add speech capabilities to their Python applications. 
 

Here's a simple example to use pyttsx3 to say "Hi" in Python:

  1. First, install pyttsx3 if you haven’t:

    pip install pyttsx3
    
  2. Then, use this code:

    import pyttsx3
    
    # Initialize the TTS engine
    engine = pyttsx3.init()
    
    # Set the text you want to say
    text = "Hi"
    
    # Use the engine to say the text
    engine.say(text)
    
    # Run and wait for the speech to complete
    engine.runAndWait()
    

This code will make your system say "Hi" using one of the available voices on your system.

 

Below is the advanced version of sample with pyttsx3 to select voice:

import pyttsx3

engine = pyttsx3.init()

# List available voices
voices = engine.getProperty('voices')

# Select a male or female voice if available
for voice in voices:
    if "female" in voice.name.lower():  # Change to "male" for a male voice
        engine.setProperty('voice', voice.id)
        break

text = "Hello, this is a sample text to speech with a selected voice."
engine.say(text)
engine.runAndWait()

 

Below case is an example to generate audio file in mp3:

import pyttsx3

# Initialize the pyttsx3 engine
engine = pyttsx3.init()

# Configure the voice properties (optional)
engine.setProperty('rate', 150)  # Speed of speech
engine.setProperty('volume', 1)  # Volume level (0.0 to 1.0)

# Choose a voice (optional)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)  # Use the first available voice

# Text to convert to speech
text = "This is a sample text to be saved as an audio file using pyttsx3."

# Save the speech to an audio file
engine.save_to_file(text, 'output_audio.mp3')
engine.runAndWait()

print("Audio file created successfully as 'output_audio.mp3'")

Explanation

  • engine.setProperty('rate', 150): Controls the speed of speech.
  • engine.setProperty('volume', 1): Sets the volume (1.0 is max).
  • engine.setProperty('voice', voices[0].id): Sets the voice (you can explore different available voices).
  • save_to_file(): Converts the text to speech and saves it as 'output_audio.mp3'.

This code will create an MP3 file called output_audio.mp3 containing the speech. pyttsx3 uses platform-specific speech synthesis engines (like SAPI5 on Windows and NSSpeechSynthesizer on macOS), so audio quality and available voices might vary depending on the operating system.


pyttsx3 is a cross-platform library and works well on Linux distributions including CentOS. It uses the system's built-in text-to-speech engine, so you won't need to install any additional dependencies. Simply install the `pyttsx3` package using `pip` and you're ready to start using it. 

 

You may also have interest to have the available voice list.

import pyttsx3

# Initialize the pyttsx3 engine
engine = pyttsx3.init()

# Get the list of available voices
voices = engine.getProperty('voices')

# Print the available voices with their details
for index, voice in enumerate(voices):
    print(f"Voice {index + 1}:")
    print(f" - ID: {voice.id}")
    print(f" - Name: {voice.name}")
    print(f" - Languages: {voice.languages}")  # Languages (if available)
    print(f" - Gender: {voice.gender}")       # Gender (if available)
    print(f" - Age: {voice.age}")             # Age (if available)
    print("\n")

# Optionally, you can also print the number of available voices
print(f"Total voices available: {len(voices)}")

Explanation

  • voice.id: A unique identifier for the voice, often used to set the voice.
  • voice.name: The name of the voice (this can vary by platform).
  • voice.languages: Languages supported by the voice (if the information is available).
  • voice.gender and voice.age: Gender and age attributes (availability depends on the platform and engine).

This code will print out all available voices, including any language information. However, pyttsx3 may not always provide specific language codes or detailed attributes depending on the operating system’s TTS engine.

Tags Python Audio Processing Python TTS Text To Audio Text To MP3 Text To Speech Text To Voice pyttsx3 Facebook X
Comments 0
Similar posts
  1. Creating mp3 audio file based on the text input with Python
    470
  2. Deleting a specific user voice from the original audio track with Python
    553
  3. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,452
  1. Method to maximize full CPU performance with Python
    325
  2. How do I get the maximum available of thread in python?
    994
  3. Using Queue Algorithm with Redis - RPUSH and LPOP
    774
  4. Use cache concept with Redis : Let's do Redis programming with Python
    539
  5. Installing Python 3.8 in a venv environment on CentOS 7
    465
  6. CUDA versus OpenCL
    584
  7. Simple gRPC server based on Python
    398
  8. Python code to convert PDF file to Excel Spreadsheet
    705
  9. Python script to list files on your Google Drive and download one of them
    941
  10. Coinbase Python API - Basic Example
    464
  11. AWS Lambda Code Example based on Python
    334
  12. Python code using GPU on CentOS with AWS
    1,258
  13. Video Scence Detection with PySceneDetect
    2,339
  14. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    912
  15. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    443
  16. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    560
  17. Python Simplified Assignment Operators
    535
  18. Trackback module used for Python Threading debugging
    847
  19. Python Flask with simple HTML files to server web pages along with API
    931
  20. Python Flask web server tutorial from the scratch
    626
  21. Simple Web Server based in Python
    381
  22. Thread Implementation in Python
    511
  23. A shell script that activates a Python virtual environment and then runs a specific Python script
    747
  24. Learning about Python Multiprocessing Technique
    594
  25. Simple Example to get the total number of records in BigQuery with Python
    668
  26. Using BigQuery in Python
    414
  27. Python Web Programming based on Django from the Scratch
    390
  28. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    193
  29. How do I determine the client IP type in Python - IPv4 or IPv6
    766
  30. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,234
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,906
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232