22
22
23
23
import io
24
24
import os
25
+ import html
25
26
# [END translate_hybrid_imports]
26
27
27
28
# [START translate_hybrid_project_id]
@@ -165,7 +166,8 @@ def translate_text(text, source_language_code, target_language_code,
165
166
166
167
# [START translate_hybrid_tts]
167
168
def text_to_speech (text , outfile ):
168
- """Generates synthetic audio from plaintext
169
+ """Converts plaintext to SSML and
170
+ generates synthetic audio from SSML
169
171
170
172
ARGS
171
173
text: text to synthesize
@@ -175,11 +177,22 @@ def text_to_speech(text, outfile):
175
177
nothing
176
178
"""
177
179
180
+ # Replace special characters with HTML Ampersand Character Codes
181
+ # These Codes prevent the API from confusing text with
182
+ # SSML commands
183
+ # For example, '<' --> '<' and '&' --> '&'
184
+ escaped_lines = html .escape (text )
185
+
186
+ # Convert plaintext to SSML in order to wait two seconds
187
+ # between each line in synthetic speech
188
+ ssml = '<speak>{}</speak>' .format (
189
+ escaped_lines .replace ('\n ' , '\n <break time="2s"/>' ))
190
+
178
191
# Instantiates a client
179
192
client = texttospeech .TextToSpeechClient ()
180
193
181
194
# Sets the text input to be synthesized
182
- synthesis_input = texttospeech .types .SynthesisInput (text = text )
195
+ synthesis_input = texttospeech .types .SynthesisInput (ssml = ssml )
183
196
184
197
# Builds the voice request, selects the language code ("en-US") and
185
198
# the SSML voice gender ("MALE")
0 commit comments