Skip to main content
Build a seamless text-to-speech pipeline in Python by combining OpenAI’s Chat API with Google’s gTTS library. Generate natural language responses from an LLM and have them spoken aloud automatically.

Prerequisites

1. Install Dependencies

This example is tested on Python 3.7+. If you use a different version, adjust commands as needed.

2. Set Your OpenAI API Key

Never commit your API key to public repositories. Use a secure vault or environment manager in production.

Imports and Client Initialization

Begin by importing standard libraries, gTTS, and initializing the OpenAI client:

1. Define the Prompt

Decide what you want the model to say. For example:

2. Text-to-Speech Function

Convert text to speech and play the resulting MP3:
Adjust the playback command (afplay, mpg123, or mpg321) based on your operating system.

3. Generate Text from OpenAI

Send the prompt to the Chat API and retrieve the response:

4. Combine Generation and Speech

Create a helper that prints the generated text, then speaks it:

5. Entry Point

Run the full pipeline with your defined prompt:

Example Console Output


Next Steps & Extensions

  • Support multiple languages by changing lang in text_to_speech().
  • Experiment with different voices and speech parameters.
  • Integrate other audio libraries like pydub or playsound for advanced playback.

Watch Video