Skip to content

Instantly share code, notes, and snippets.

@divadsn
Created August 14, 2020 15:29
Show Gist options
  • Save divadsn/0f37262c09881412e92f962b5583b89f to your computer and use it in GitHub Desktop.
Save divadsn/0f37262c09881412e92f962b5583b89f to your computer and use it in GitHub Desktop.
Why even use the entire SDK lul...
import base64
import json
import requests
class TTSException(Exception):
def __init__(self, code: int, message: str, status: str):
self.code = code
self.message = message
self.status = status
class TextToSpeech(object):
def __init__(self, api_key: str, audio_config: dict = {"audioEncoding": "MP3"}):
self.api_key = api_key
self.audio_config = audio_config
def create_voice(self, language: str = "en-US", type: str = "Standard-A", gender: str = "FEMALE"):
return {
"languageCode": language,
"name": "%s-%s" % (language, type),
"ssmlGender": gender.upper()
}
def get_audio(self, text: str, voice: dict = {"languageCode": "en-US", "name": "en-US-Standard-A", "ssmlGender": "FEMALE"}):
r = requests.post(
url="https://texttospeech.googleapis.com/v1/text:synthesize",
json={
"input": {"text": text},
"voice": voice,
"audioConfig": self.audio_config
},
headers={
"X-Goog-Api-Key": self.api_key,
"Content-Type": "application/json; charset=utf-8"
}
)
data = r.json()
if r.status_code != 200 and "error" in data:
error = data["error"]
raise TTSException(error["code"], error["message"], error["status"])
return base64.b64decode(data["audioContent"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment