Created
August 21, 2024 19:29
-
-
Save dvir1994/471de096e5e65893740b88f0cebbc2b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
# Constants | |
ELEVEN_LABS_API_KEY = "XYZ" | |
ELEVEN_LABS_VOICE_ID = "EXAVITQu4vr4xnSDxMaL" # Voice ID can be found here - https://elevenlabs.io/docs/api-reference/get-voices | |
ELEVEN_LABS_TTS_API_ENDPOINT = ( | |
f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVEN_LABS_VOICE_ID}" | |
) | |
OUTPUT_FILE_PATH = "/tmp/output.mp3" | |
# Text to be converted to speech | |
text = "Hello! My name is Ben and I am building the best Gladiators game ever!" | |
# Headers for the API request | |
headers = { | |
"Accept": "audio/mpeg", | |
"Content-Type": "application/json", | |
"xi-api-key": ELEVEN_LABS_API_KEY, | |
} | |
# Data payload for the API request | |
data = { | |
"text": text, | |
"model_id": "eleven_monolingual_v1", | |
"voice_settings": {"stability": 0.5, "similarity_boost": 0.5}, | |
} | |
try: | |
# Send POST request to the API | |
response = requests.post(ELEVEN_LABS_TTS_API_ENDPOINT, json=data, headers=headers) | |
# Check if the request was successful | |
if response.status_code == 200: | |
# Save the audio content to an MP3 file | |
with open(OUTPUT_FILE_PATH, "wb") as audio_file: | |
audio_file.write(response.content) | |
print("Audio file saved successfully as 'output.mp3'") | |
else: | |
print(f"Error: Received status code {response.status_code}") | |
print(response.text) | |
except Exception as e: | |
print(f"An error occurred: {str(e)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment