OpenAI Text to Speech (TTS): Minimal Example in Python

5/5 - (9 votes)

To use OpenAI’s amazing Text-to-Speech (TTS) functionality, first install the openai Python library and obtain an API key from OpenAI.

Instantiate an OpenAI client with openai.OpenAI(api_key).

Call client.audio.speech.create(model='tts_1', voice='alloy', input=your_text) to use the 'alloy' voice model.

This generates speech you can save as an MP3 file using response.stream_to_file('your_file.mp3').


First, install the OpenAI library and set up your OpenAI key.

pip install openai # Python 2 or 3
pip3 install openai # Python 3 
!pip install openai # Google Colab

πŸ§‘β€πŸ’» Recommended: How to Install OpenAI in Python?

Second, copy and paste the following code in your Pythons script or notebook, replacing the OpenAI API key with your own.

import openai

your_openai_key = 'sk-...'
your_text = 'Finxter helps you stay on the right side of change!'

client = openai.OpenAI(api_key=your_openai_key)

response = client.audio.speech.create(
  model="tts-1",
  voice="alloy", # other voices: 'echo', 'fable', 'onyx', 'nova', 'shimmer'
  input=your_text
)

response.stream_to_file('speech.mp3')

You can now find the file 'speech.mp3' in the same folder where you ran your Python script. Easy as that!

Now check out the amazing voice that sounds like a genuine human being, doesn’t it? πŸ‘‡

At the time of writing, you can use the following voices:

voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']

Here are the six different voices in that order:

πŸ‘¨ Alloy (male):

πŸ‘¨β€πŸ¦² Echo (male):

πŸ¦„ Fable (female?):

πŸ‘© Onyx (female):

πŸ§“ Nova (deep male):

πŸ’ƒ Shimmer (female):


Staying tuned in these rapidly changing times is crucial. Feel free to join our free email newsletter by downloading our Python and OpenAI cheat sheets:

Also, you can take our prompt engineering courses for premium success:

Prompt Engineering with Llama 2

πŸ’‘ TheΒ Llama 2 Prompt Engineering course helps you stay on the right side of change.Β Our course is meticulously designed to provide you with hands-on experience through genuine projects.

You’ll delve into practical applications such as book PDF querying, payroll auditing, and hotel review analytics. These aren’t just theoretical exercises; they’re real-world challenges that businesses face daily.

By studying these projects, you’ll gain a deeper comprehension of how to harness the power of Llama 2 using 🐍 Python, πŸ”—πŸ¦œ Langchain, 🌲 Pinecone, and a whole stack of highly βš’οΈπŸ› οΈ practical tools of exponential coders in a post-ChatGPT world.