Creating mp3 audio file based on the text input with Python

CK CK 3788 
Created at
Updated at  
464 0 0

gTTS (Google Text-to-Speech) is a free and easy-to-use Python library that allows you to convert text into spoken audio using Google's powerful text-to-speech engine. Its benefits include simple implementation, support for multiple languages and accents, customizable speech parameters like speed and pitch, and the ability to save the output as MP3 files, making it ideal for projects requiring audio generation, accessibility features, or interactive applications. 
 

gTTS, a text-to-speech library, offers a variety of voice types, but the specific options vary depending on the language selected. While some languages may have a wider range of voices, including male, female, and even different accents, others might only offer a single default voice. You can explore the available voices for a particular language by using the `languages()` method and then selecting the desired voice within the `t2s()` method.

 

To create a voice (speech) file using Google Text-to-Speech (gTTS) in Python, you can use the following code. This will convert text to speech and save it as an audio file (e.g., in MP3 format).

First, install gTTS if you haven't already:

pip install gTTS

Then, use this code to create a voice file:

from gtts import gTTS

# Text you want to convert to audio
text = "Hello, this is a sample text converted to speech using gTTS in Python."

# Specify language (e.g., 'en' for English, 'es' for Spanish)
language = 'en'

# Create a gTTS object
tts = gTTS(text=text, lang=language, slow=False)

# Save the audio file
tts.save("output.mp3")

print("Voice file created successfully!")

Explanation

  • text: The text you want to convert to speech.
  • lang: Set the language code for the text (e.g., 'en' for English).
  • slow=False: Controls the speed; False for normal speed, True for slower speed.
  • save("output.mp3"): Saves the output file as output.mp3 in the working directory.

Once the script is run, you’ll get an output.mp3 file with the spoken text. You can adjust the text and language as needed.

 

If you have an API key for GCP(Google Cloud Platform), you can do more:

The gTTS library itself doesn’t directly provide a list of available voices, as it only supports specifying language codes (like 'en' for English, 'fr' for French, etc.) and a speed setting (slow=True/False). It defaults to using Google's standard voice for each language. However, Google Text-to-Speech does support various voices, but to access them, you would need to use the Google Cloud Text-to-Speech API, which provides more control over different voices and accents.

If you’d like a sample code for listing voices using the Google Cloud Text-to-Speech API, here’s how:

  1. First, set up the Google Cloud Text-to-Speech API on Google Cloud Console.
  2. Install the google-cloud-texttospeech library:

    pip install google-cloud-texttospeech
    
  3. Then, use the following code to list available voices:

    from google.cloud import texttospeech
    
    # Initialize the client
    client = texttospeech.TextToSpeechClient()
    
    # Retrieve the list of voices
    voices = client.list_voices()
    
    # Print the available voices
    for voice in voices.voices:
        print(f"Name: {voice.name}")
        print(f"Language Codes: {', '.join(voice.language_codes)}")
        print(f"SSML Gender: {texttospeech.SsmlVoiceGender(voice.ssml_gender).name}")
        print(f"Natural Sample Rate Hertz: {voice.natural_sample_rate_hertz}\n")
    

Explanation

  • texttospeech.TextToSpeechClient(): Initializes the client for Google Cloud Text-to-Speech.
  • list_voices(): Lists all available voices, with details like name, supported languages, gender, and sample rate.

Output Example

The script will output a list of voices available, including the voice name, language codes, SSML gender (e.g., MALE, FEMALE), and sample rate.

Note: Using Google Cloud Text-to-Speech requires setting up a Google Cloud project, enabling billing, and authenticating using a service account file.

Tags GCP Google Cloud Platform Python Audio Processing TTS Text To Speech gTTS google-cloud-texttospeech Facebook X
Comments 0
Similar posts
  1. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
  2. Deleting a specific user voice from the original audio track with Python
    547
  3. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,433
  1. Using Queue Algorithm with Redis - RPUSH and LPOP
    767
  2. Use cache concept with Redis : Let's do Redis programming with Python
    528
  3. Installing Python 3.8 in a venv environment on CentOS 7
    461
  4. CUDA versus OpenCL
    577
  5. Simple gRPC server based on Python
    393
  6. Python code to convert PDF file to Excel Spreadsheet
    695
  7. Python script to list files on your Google Drive and download one of them
    939
  8. Coinbase Python API - Basic Example
    461
  9. AWS Lambda Code Example based on Python
    333
  10. Python code using GPU on CentOS with AWS
    1,248
  11. Video Scence Detection with PySceneDetect
    2,318
  12. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,433
  13. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    902
  14. Deleting a specific user voice from the original audio track with Python
    547
  15. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  16. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
  17. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  18. Python Simplified Assignment Operators
    533
  19. Trackback module used for Python Threading debugging
    840
  20. Python Flask with simple HTML files to server web pages along with API
    926
  21. Python Flask web server tutorial from the scratch
    618
  22. Simple Web Server based in Python
    368
  23. Thread Implementation in Python
    508
  24. A shell script that activates a Python virtual environment and then runs a specific Python script
    741
  25. Learning about Python Multiprocessing Technique
    591
  26. Simple Example to get the total number of records in BigQuery with Python
    665
  27. Using BigQuery in Python
    407
  28. Python Web Programming based on Django from the Scratch
    366
  29. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  30. How do I determine the client IP type in Python - IPv4 or IPv6
    760
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,727
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252