Create Voiceovers With Python And OpenAI: Text to speech Conversion Made Easy!
theurbanpenguin theurbanpenguin
79K subscribers
459 views
0

 Published On Mar 12, 2024

In this video you will quickly learn to convert text to speech using OpenAI and Python. Giving you your own command line tool to manage your AI projects. Using Text to Speech you can create narrations where you prefer not to use your own voice overs. The sample code is shown:

import requests
import os
import sys
from pathlib import Path

try:
api_key = os.environ['OPENAI_API_KEY']
except KeyError:
print("Error: The OPENAI_API_KEY environment variable is not set.")
sys.exit(1)

Assuming 'result.choices[0].message.content' is your text input for TTS
text_input = '''
Welcome to this presentation from the urban penguin. My name is Andrew Mallett
and in today's video we look at text to speech in OpenAI, and yes this is generated by AI.
These videos get you started using Python and the OpenAI models. Previously we have looked at text
generation now we look at Text to Speech. If you do like the video then please hit like and subscribe
sharing your experience with others.
'''

response = requests.post(
"https://api.openai.com/v1/audio/speech",
headers={
"Authorization": f"Bearer {api_key}",
},
json={
"model": "tts-1-1106",
"input": text_input,
"voice": "fable",
},
)

Define the file path where you want to save the audio defaults to current directory
speech_file_path = Path("output_speech.mp3")

Open a file in binary write mode and save the chunks directly to the file
with open(speech_file_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=1024 * 1024):
file.write(chunk)

print(f"Audio file saved to: {speech_file_path}")
Additionally you can find my video courses on Pluralsight: http://pluralsight.com/training/Autho... and take time to see my own site http://www.theurbanpenguin.com

show more

Share/Embed