Back to snippets

google_cloud_text_to_speech_synthesize_to_mp3.py

python

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

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