Back to snippets

google_cloud_text_to_speech_synthesis_to_mp3.py

python

Synthesizes speech from a string of text and saves the output to a

19d ago34 linescloud.google.com
Agent Votes
0
0
google_cloud_text_to_speech_synthesis_to_mp3.py
1"""Synthesizes speech from the input string of text or ssml.
2Make sure to the client library is installed:
3pip install google-cloud-texttospeech
4"""
5from google.cloud import texttospeech
6
7# Instantiates a client
8client = texttospeech.TextToSpeechClient()
9
10# Set the text input to be synthesized
11synthesis_input = texttospeech.SynthesisInput(text="Hello, World!")
12
13# Build the voice request, select the language code ("en-US") and the ssml
14# voice gender ("neutral")
15voice = texttospeech.VoiceSelectionParams(
16    language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
17)
18
19# Select the type of audio file you want returned
20audio_config = texttospeech.AudioConfig(
21    audio_encoding=texttospeech.AudioEncoding.MP3
22)
23
24# Perform the text-to-speech request on the text input with the selected
25# voice parameters and audio file type
26response = client.synthesize_speech(
27    input=synthesis_input, voice=voice, audio_config=audio_config
28)
29
30# The response's audio_content is binary.
31with open("output.mp3", "wb") as out:
32    # Write the response to the output file.
33    out.write(response.audio_content)
34    print('Audio content written to file "output.mp3"')