-
Notifications
You must be signed in to change notification settings - Fork 0
/
texttospeech.py
33 lines (26 loc) · 1000 Bytes
/
texttospeech.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import requests
import os
def generate_speech(input_text, output_file, api_key):
url = "https://api.openai.com/v1/audio/speech"
headers = {
"Authorization": "Bearer " + api_key,
"Content-Type": "application/json"
}
payload = {
"model": "tts-1",
"input": input_text,
"voice": "alloy"
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status() # Raise an exception for 4xx or 5xx errors
with open(output_file, "wb") as f:
f.write(response.content)
print("Speech generated successfully. Output file:", output_file)
except requests.exceptions.RequestException as e:
print("Error generating speech:", e)
# Example usage
api_key = "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"
input_text = "Today is a wonderful day to build something people love!"
output_file = "speech.mp3"
generate_speech(input_text, output_file, api_key)