Skip to content

Instantly share code, notes, and snippets.

@armindocachada
Created July 21, 2020 15:32
Show Gist options
  • Save armindocachada/ab7b88abab6b848b67cb38e5b239bd7c to your computer and use it in GitHub Desktop.
Save armindocachada/ab7b88abab6b848b67cb38e5b239bd7c to your computer and use it in GitHub Desktop.
Calling the Google Text To Speech API
def text_to_speech(speak, languageCode, outputFilePath, speed=1.0):
"""Synthesizes speech from the input string of text or ssml.
Note: ssml must be well-formed according to:
https://www.w3.org/TR/speech-synthesis/
"""
from google.cloud import texttospeech
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(text=speak)
# Build the voice request, select the language code ("en-US") and the ssml
# voice gender ("neutral")
voice = texttospeech.VoiceSelectionParams(
language_code=languageCode, ssml_gender=texttospeech.SsmlVoiceGender.MALE
)
# Select the type of audio file you want returned
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3,
speaking_rate=speed
)
# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(
input=synthesis_input, voice=voice, audio_config=audio_config
)
# The response's audio_content is binary.
with open(outputFilePath, "wb") as out:
# Write the response to the output file.
out.write(response.audio_content)
print('Audio content written to file "{}"'.format(outputFilePath))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment