Generate speech from the given text using OpenAI in Python

See how to generate and play speech from text using OpenAI in Python. This notebook covers setting a file path, creating an API request, saving the response as an MPR3 file and playing the audio.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

All of the required packages are imported automatically by MLJAR Studio.

# import packages
import os
from dotenv import load_dotenv
from openai import OpenAI, AuthenticationError
from IPython.display import Audio

Create OpenAI client connection:

# load .env file
load_dotenv()

# get api key from environment
api_key = os.environ["OPENAI_KEY"]

# create OpenAI client
def create_client(api_key):
    try:
        client = OpenAI(api_key=api_key)
        client.models.list()
        return client
    except AuthenticationError:
        print("Incorrect API")
    return None

client = create_client(api_key)

The code recipe below allows you to generate the speech from the given text:

# set file path
file_path = os.path.join(r"../../../../demo", "speech.mp3")

# create api request 
with client.audio.speech.with_streaming_response.create(
  model="tts-1",
  voice="alloy",
  input="Hi everyone! I'm here to tell you about our new product - MLJAR Studio which we made to make programming easier."
) as response:
  response.stream_to_file(file_path)

# play audio
Audio(file_path, autoplay=False)

Conclusions

Here is another way you can use OpenAI modules. Speech generation can be very useful in creating any social media activity.

Follow us for more!

Recipes used in the python-text-to-speech.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-text-to-speech.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.

openai>=1.35.14

python-dotenv>=1.0.1