Checkpoints
Enable the Text-to-Speech API
/ 50
Create a service account
/ 50
It Speaks! Create Synthetic Speech Using Text-to-Speech
GSP222
Overview
The Text-to-Speech API lets you create audio files of machine-generated, or *synthetic, *human speech. You provide the content as text or Speech Synthesis Markup Language (SSML), specify a voice (a unique 'speaker' of a language with a distinctive tone and accent), and configure the output; the Text-to-Speech API returns to you the content that you sent as spoken word, audio data, delivered by the voice that you specified.
In this lab you will create a series of audio files using the Text-to-Speech API, then listen to them to compare the differences.
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
To complete this lab, you need:
- Access to a standard internet browser (Chrome browser recommended).
- Time to complete the lab---remember, once you start, you cannot pause a lab.
How to start your lab and sign in to the Google Cloud Console
-
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:
- The Open Google Console button
- Time remaining
- The temporary credentials that you must use for this lab
- Other information, if needed, to step through this lab
-
Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account. -
If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.
-
Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.
Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges. -
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (because this is a temporary account).
- Do not sign up for free trials.
After a few moments, the Cloud Console opens in this tab.
Activate Cloud Shell
Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.
- Click Activate Cloud Shell
at the top of the Google Cloud console.
When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:
gcloud
is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
-
(Optional) You can list the active account name with this command:
-
Click Authorize.
-
Your output should now look like this:
Output:
-
(Optional) You can list the project ID with this command:
Output:
Example output:
gcloud
, in Google Cloud, refer to the gcloud CLI overview guide.
Task 1. Enable the Text-to-Speech API
- Select the APIs and Services dashboard from the drop down.
-
On the Dashboard, click Enable APIs and Services.
-
Enter for "text-to-speech" in the search box.
-
Click Cloud Text-to-Speech API.
-
In the Cloud Text-toSpeech API dialog boc, click Enable to enable the Text-to-Speech API.
Wait for a few seconds for the API to be enabled for the project. You will see this once it's enabled:
Click Check my progress to verify the objective.
Task 2. Create a virtual environment
Python virtual environments are used to isolate package installation from the system.
-
Install the
virtualenv
environment:
-
Build the virtual environment:
-
Activate the virtual environment.
Task 3. Create a service account
You should use a service account to authenticate your calls to the Text-to-Speech API.
-
To create a service account, run the following command in Cloud Shell:
For this next step, you need to copy the name of your Google Cloud project.
-
Run the following command and copy the output:
Now you need to generate a key to use that service account.
-
To create and download a key, run the following command in Cloud Shell, replacing [
PROJECT_ID]
with the ID of your Google Cloud project (that you copied in the previous step):
-
Finally, set the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to the location of your key file:
Click Check my progress to verify the objective.
Task 4. Get a list of available voices
As mentioned previously, the Text-to-Speech API provides many different voices and languages that you can use to create audio files. You can use any of the available voices as the speaker for your content.
-
The following
curl
command gets the list of all the voices you can select from when creating synthetic speech using the Text-to-Speech API:
The Text-to-Speech API returns a JSON-formatted result that looks similar to the following:
Looking at the results from the curl
command, you'll notice that each voice has four fields:
-
name
: The ID of the voice that you provide when you request that voice. -
ssmlGender
: The gender of the voice to speak the text, as defined in the SSML W3 Recommendation. -
naturalSampleRateHertz
: The sampling rate of the voice. -
languageCodes
: The list of language codes associated with that voice.
You'll also notice that some languages have several voices to choose from.
-
You can scope the results returned from the API to just a single language code by running:
Task 5. Create synthetic speech from text
Now that you've seen how to get the names of voices to speak your text, it's time to create some synthetic speech!
For this, you'll build your request to the Text-to-Speech API in a text file titled synthesize-text.json
.
-
Create this file in Cloud Shell by running the following command:
-
Using a line editor (
nano
,vim
,etc
.) or the Cloud Shell code editor, create a file calledsynthesize-text.json
and paste the following into the file:
The JSON-formatted request body provides three objects:
-
The
input
object provides the text to translate into synthetic speech. -
The
voice
object specifies the voice to use for the synthetic speech. -
The
audioConfig
object tells the Text-to-Speech API what kind of audio encoding to send back.
-
Use the following code to call the Text-to-Speech API using the
curl
command:
The output of this call is saved to a file called synthesize-text.txt
.
-
Open the
synthesize-text.txt
file. You'll notice that the Text-to-Speech API provides the audio output in base64-encoded text assigned to theaudioContent
field, similar to what's shown below:
To translate the response into audio, you need to select the audio data it contains and decode it into an audio file - for this lab, MP3. Although there are many ways that you can do this, in this lab you'll use some really simple Python code. Don't worry if you're not a Python expert; you need only create the file and invoke it from the command line.
-
Create a file named
tts_decode.py
and add the following code into that file:
-
Now, to create an audio file from the response you received from the Text-to-Speech API, run the following command from Cloud Shell:
This creates a new MP3 file named synthesize-text-audio.mp3
.
Of course, since the synthesize-text-audio.mp3
lives in the cloud, you can't just play it directly from Cloud Shell! To listen to the file, you can create a Web server hosting a simple web page that embeds the file as playable audio (from an HTML <audio>
control).
-
Open the Cloud Shell Code Editor by clicking on the pencil icon (
):
-
Create a new file called
index.html
, then paste the following HTML into the file:
-
Back in Cloud Shell, start a simple Python HTTP server from the command prompt:
-
Finally, click Web Preview (
).
-
Then select the 8080 port number from the displayed menu.
In the new browser window, you should see something like the following:
-
Play the audio embedded on the page. You'll hear the synthetic voice speak the text that you provided to it!
-
When you're done listening to the audio files, you can shut down the HTTP server by pressing CTRL + C in Cloud Shell.
Task 6. Create synthetic speech from SSML
In addition to using text, you can also provide input to the Text-to-Speech API in the form of Speech Synthesis Markup Language (SSML). SSML defines an XML format for representing synthetic speech. Using SSML input, you can more precisely control pauses, emphasis, pronunciation, pitch, speed, and other qualities in the synthetic speech output.
-
First, build your request to the Text-to-Speech API in a text file titled
synthesize-ssml.json
. Create this file in Cloud Shell by running the following command:
-
Using a line editor (
nano
,vim
,emacs
) or the Cloud Shell code editor, paste the following JSON into thesynthesize-ssml.json
file:
Notice that the input
object of the JSON payload to send includes some different stuff this time around. Rather than a text
field, the input
object has a ssml
field instead. The ssml
field contains XML-formatted content the <speak>
element as its root. Each of the elements present in this XML representation of the input affects the output of the synthetic speech.
Specifically, the elements in this sample have the following effects:
-
<s>
contains a sentence. -
<emphasis>
adds stress on the enclosed word or phrase. -
<break>
inserts a pause in the speech. -
<prosody>
customizes the pitch, speaking rate, or volume of the enclosed text, as specified by therate
,pitch
, orvolume
attributes. -
<say-as>
provides more guidance about how to interpret and then say the enclosed text, for example, whether to speak a sequence of numbers as ordinal or cardinal. -
<sub>
specifies a substitution value to speak for the enclosed text.
-
In Cloud Shell use the following code to call the Text-to-Speech API, which saves the output to a file called
synthesize-ssml.txt
:
Again, you need to decode the output from the Text-to-Speech API before you can hear the audio.
-
Run the following command to generate an audio file named
synthesize-ssml-audio.mp3
using thetts_decode.py
utility that you created previously:
-
Next, open the
index.html
file that you created earlier. Replace the contents of the file with the following HTML:
-
Then, start a simple Python HTTP server from the Cloud Shell command prompt:
- As before, click Web Preview
and then select the port number from the displayed menu. In the new browser window, you should see something like the following:
-
Play the two embedded audio files. Notice the differences in the SSML output: although both audio files say the same words, the SSML output speaks them a bit differently, adding pauses and different pronunciations for abbreviations.
Task 7. Configure audio output and device profiles
Going beyond SSML, you can provide even more customization to your synthetic speech output created by the Text-to-Speech API. You can specify other audio encodings, change the pitch of the audio output, and even request that the output be optimized for a specific type of hardware.
Build your request to the Text-to-Speech API in a text file titled synthesize-with-settings.json
.
-
To do this, create this file in Cloud Shell by running the following command:
-
Using a line editor (
nano
,vim
,emacs
) or the Cloud Shell code editor, paste the following JSON into thesynthesize-with-settings.json
file:
Looking at this JSON payload, you notice that the audioConfig
object contains some additional fields now:
- The
speakingRate
field specifies a speed at which the speaker says the voice. A value of 1.0 is the normal speed for the voice, 0.5 is half that fast, and 2.0 is twice as fast. - The
pitch
field specifies a difference in tone to speak the words. The value here specifies a number of semitones lower (negative) or higher (positive) to speak the words. - The
audioEncoding
field specifies the audio encoding to use for the data. The accepted values for this field areLINEAR16
,MP3
, andOGG_OPUS
. - The
effectsProfileId
field requests that the Text-to-Speech API optimizes the audio output for a specific playback device. The API applies an predefined audio profile to the output that enhances the audio quality on the specified class of devices.
-
Use the following code to call the Text-to-Speech API using the
curl
command:
The output of this call is saved to a file called synthesize-with-settings.txt
.
-
Run the following command to generate an audio file named
synthesize-with-settings-audio.mp3
from the output received from the Text-to-Speech API:
-
Next open the
index.html
file that you created earlier and replace the contents of the file with the following HTML:
-
Now, restart the Python HTTP server from the Cloud Shell command prompt:
- As before, click Web Preview
then select the port number from the displayed menu.
In the new browser window, you should see something like the following:
-
Play the third embedded audio file. Notice that the voice on the audio speaks a bit faster and lower than the previous examples.
Congratulations!
You have learned how to create synthetic speech using the Cloud Text-to-Speech API. You learned about:
-
Listing all of the synthetic voices available through the Text-to-Speech API
-
Creating a Text-to-Speech API request and calling the API with curl, providing both text and SSML
-
Configuring the setting for audio output, including specifying a device profile for audio playback
Finish your quest
This self-paced lab is part of the Language, Speech, Text & Translation with Google CLoud APIs quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest and get immediate completion credit. Refer to the Google Cloud Skills Boost catalog for all available quests.
Take your next lab
Continue your quest with Translate Text with the Cloud Translation API or try one of these:
Next steps / learn more
- Check out the detailed documentation for the Text-to-Speech API on cloud.google.com.
- Learn how to create synthetic speech using the client libraries for the Text-to-Speech API.
Google Cloud training and certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.
Manual Last Updated September 7, 2022
Lab Last Tested August 13, 2019
Copyright 2023 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.