Skip to content

Instantly share code, notes, and snippets.

@sarkrui
Created September 29, 2020 08:08
Show Gist options
  • Save sarkrui/b0c5e4b0194bba3b479b5009675be162 to your computer and use it in GitHub Desktop.
Save sarkrui/b0c5e4b0194bba3b479b5009675be162 to your computer and use it in GitHub Desktop.
Google Cloud Text-to-Speech API
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/path/to/your/json.json"
from google.cloud import texttospeech
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(
text="Ladies and Gentlemen, It is a pleasure for me to be here tonight and address such a great audience. \
The issue I would like to bring up threatens the prosperity and welfare of the whole nation, \
however, the majority of the population tends to ignore it and pretend as if it is not a problem at all.\
Namely, I would like to talk about the risks of obesity.")
# Build the voice request, select the language code ("en-US") and the ssml
# voice gender ("female")
voice = texttospeech.VoiceSelectionParams(
language_code='en-US',
name='en-US-Wavenet-J',
ssml_gender=texttospeech.SsmlVoiceGender.MALE)
# Select the type of audio file you want returned
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3)
# 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('output.mp3', 'wb') as out:
# Write the response to the output file.
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
@sarkrui
Copy link
Author

sarkrui commented Sep 29, 2020

Click here to view the output sample.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment