Table of Contents
Overview
The Google Cloud Speech streaming API enables developers to turn spoken language into text in real time. Using the API in combination with Javascript's Web Audio API and Websockets, a Java servlet can accept streamed speech from a webpage and provide text transcripts of it, enabling any web page to use the spoken word as an additional user interface.
This lab is split into multiple sections, each section introduces a component of the final web application.
The webapp you create takes audio from the client's microphone and streams it to a Java servlet. The Java servlet passes the data to the Cloud Speech API, which streams transcriptions of any speech it detects back to the servlet. The servlet then passes the transcription results to the client, which then displays it on the page.
To accomplish this, you need to create several components:
A Java servlet to serve the static HTML, Javascript, and CSS for the web page.
The Javascript, HTML, and CSS to connect the webpage to the user's microphone, extract the raw bytes, and stream them to the servlet through a Websocket.
A servlet Websocket handler to stream the sound bytes it receives from the client to the Cloud Speech API, and streams the transcription results from the Cloud Speech API back to the client.
What you'll do
Create a virtual machine (VM)
Start an HTTP Java servlet
Capture audio on a webpage
Transcribe voice to text
Prerequisites
This lab assumes familiarity with:
The Java programming language.
Java servlets (specifically, the Jetty servlet container). While other servlet containers can be used, the sample solution uses Jetty, making solutions using other containers harder to verify against.
The Javascript programming language. Code for webpages are done almost exclusively in Javascript, and a lab about a webpage would be hard-pressed to avoid using it.
The Linux command line. Much of the lab takes place at a Linux command prompt, and familiarity with some common tools and a text editor for that environment makes things easier.
The Maven project management tool. While in principle, any Java project management tool can be used, the sample solution uses Maven, making solutions using other tools harder to verify against.
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 are made available to you.
This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials 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).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
- Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.
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 dialog opens for you to select your payment method. On the left is the Lab Details pane with the following:
The Open Google Cloud 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 Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).
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 below and paste it into the Sign in dialog.
student-04-99487e535162@qwiklabs.net
You can also find the Username in the Lab Details pane.
Click Next.
Copy the Password below and paste it into the Welcome dialog.
W0HcUVjwxlz5
You can also find the Password in the Lab Details pane.
Click Next.
Important: You must use the credentials the lab provides you. Do not use your Google Cloud account 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 Google Cloud console opens in this tab.
Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field.
Task 1. Create a virtual machine
Compute Engine is a service that allows you to start VMs on Google's infrastructure. In this lab, you create and use a VM to run a servlet written in Java 8 that hosts the website and use the Cloud Speech API to provide dynamic transcriptions to the client. For the purposes of this lab, you also use the VM to run your code.
To create a new VM, click the Navigation menu () > Compute Engine > VM instances.
To create a new instance, click Create Instance.
In the Machine configuration.
Name the new instance
speaking-with-a-webpage
.Choose a zone as
us-east1-d
.Leave the other values as default.
Click OS and storage.
Click Change to begin configuring your boot disk and select the following values:
For Operating system select Debian.
For Version select Debian GNU/Linux 11 (bullseye).
Leave the Boot disk type set to default.
At the bottom of the window, click Select.
Click Networking.
- For Firewall check for Check Allow HTTP traffic and Check Allow HTTPS traffic.
Click Security.
For Identity and API access > Service Account leave as default.
For Access scopes select Allow full access to all Cloud APIs.
Click Create.
After a few minutes, your VM is up and running! View your VM and its details in the VM instances list. Notice the SSH button to use in the next step, and the External IP to use later in this lab.
- Connect to it by clicking the SSH button to its right. If prompted, click Authorize.
A new window opens and connects you to your VM, providing a command prompt. Use this interface for the rest of this lab.
Test completed task
Click Check my progress to verify your performed task.
Create a virtual machine
Check my progress
Relevant documentation
Read more about Compute Engine and its different capabilities in the Compute Engine documentation reference.
Task 2. Download and set up a working example
- In the SSH session, install Git and the example here, uses Java 11 and the Maven project management tool to compile and run its code. Install them on your VM:
sudo apt update && sudo apt install git -y
sudo apt-get install -y maven openjdk-11-jdk
Note: This command may take a couple of minutes.
- Clone the working example to your VM:
git clone https://github.com/googlecodelabs/speaking-with-a-webpage.git
This creates the directory, speaking-with-a-webpage
, which contains subdirectories for each of the following sections. Each subdirectory builds on the one before it, incrementally adding new functionality:
01-hello-https
- contains a minimal Jetty servlet with static files and a handler served over HTTPS02-webaudio
- fills out the client-side Javascript to record audio from the client's microphone and display a visualization to confirm it works03-websockets
- modifies both the client and the server to communicate with each other through a websocket04-speech
- modifies the server to send audio to the Cloud Speech API, and send subsequent transcriptions to the Javascript client
The example used for this lab does not use the normal HTTPS port - instead, they use the non-privileged port 8443
, for development purposes.
- In order to access this port from your web browser, open your VM's firewall using this gcloud command:
gcloud compute firewall-rules create dev-ports \
--allow=tcp:8443 \
--source-ranges=0.0.0.0/0
Note: You can compare what changed between steps.
If you'd like to compare what changed between one section and the next, you can use the following command:
cd ~/speaking-with-a-webpage
git diff --no-index 01-hello-https/ 02-webaudio/
This displays the differences between the 02-https
and 03-webaudio
directories / steps.
Use the arrow keys, PgUp / PgDn to navigate, and q
to quit.
Test completed task
Click Check my progress to verify your performed task.
Install necessary software and create a firewall rule
Check my progress
Task 3. Start the HTTPS Java Servlet
The Java Servlet is the backbone that supports this webapp, as it serves the required client-side HTML, CSS, and Javascript code, and connects to the Cloud Speech API to provide transcriptions.
When accessing a user's microphone from a webpage, browsers require the webpage to communicate over a secure channel to prevent eavesdropping. Because of this, set up your servlet to serve webpages over HTTPS. Since configuring and serving secure web pages is a topic in itself, for this lab use the self-signed certificate and Jetty configuration files in the provided sample solution, which is sufficient for a development environment.
For this section, simply read through and run the provided Maven project in 01-hello-https
. Take particular note of the files within the src/
directory, as those are the primary files that are built on in subsequent steps:
The files in
src/main/webapp
include the Javascript, CSS, and HTML files, that are served statically by JettyTranscribeServlet.java
defines the servlet that handles requests to the path/transcribe
Running the sample solution
The 01-hello-https subdirectory of the provided speaking-with-a-webpage
repository contains a Maven servlet project configured for HTTPS. This servlet uses the Jetty servlet framework to serve both static files and a dynamic endpoint. It also uses the blog post above to generate a self-signed certificate using the Key Tool command, and adds Jetty configuration to support HTTPS.
- Start the servlet. Navigate to
01-hello-https.
cd ~/speaking-with-a-webpage/01-hello-https
- Run the code:
mvn clean jetty:run
- Then point your web browser to:
https://<your-external-ip>:8443
Note: You can find your external IP address on the Cloud Console VM Instances page.
Because the sample servlet is listening on a non-standard port, clicking the External IP link directly does not direct you to your running servlet. You have to add the relevant port, as above, to access your servlet.
When you first access the webapp using the HTTPS URL, your browser will likely warn you that the connection is not private. This is because the sample app uses a self-signed SSL certificate for development. In a production environment, you would need an SSL certificate signed by a Certificate Authority, but for the purposes of this lab, a self-signed SSL certificate suffices. Just be sure not to speak of any secrets with your web page. 😁
Test completed task
Click Check my progress to verify your performed task.
Run the sample solution (hello-https)
Check my progress
Task 4. Capture audio on a webpage
The Web Audio API allows a webpage to capture audio data from a user's microphone, given their consent. The Cloud Speech API needs this raw data in a certain form, and needs to know the rate at which it's sampled.
Sample solution
The 02-webaudio
subdirectory of the provided speaking-with-a-webpage
repository builds on the 01-hello-https
sample code by adding the Web Audio getUserMedia function to connect the user's microphone to a visualization of the audio. It then adds a ScriptProcessorNode to the audio pipeline to retrieve the raw audio bytes, in preparation for sending it to the server. Since the Cloud Speech API will also eventually need the sampleRate, it retrieves that as well. Start the 02-webaudio
app as follows:
Press CTRL+C to stop the server.
Navigate to the directory that contains
02-webaudio
:
cd ~/speaking-with-a-webpage/02-webaudio
- Run the application:
mvn clean jetty:run
- To access your running webapp, look for the External IP address in your Cloud Console VM Instances page, and point your browser to:
https://<your-external-ip>:8443
Note: You can check what's changed between the previous section (01-hello-https
) and the current one (02-webaudio
) by running:
cd ~/speaking-with-a-webpage
git diff --no-index 01-hello-https/ 02-webaudio/
Test completed task
Click Check my progress to verify your performed task.
Run the sample solution to capture audio on webpage
Check my progress
- Press CTRL+C to stop the server.
Task 5. Stream audio from client to server
A normal HTTP connection is not ideal for realtime streaming of audio to a server, while receiving transcriptions as they become available. In this section, you create a Web Socket connection from the client to the server, and use it to send along the audio metadata (i.e.,the sample rate) and data to the server, while listening for a response (i.e., the transcript of the data).
Streaming audio bytes
The provided example changes the TranscribeServlet to extend from WebSocketServlet
in order to register a WebSocketAdapter
. The WebSocketAdapter
it defines simply takes the message it's received and sends it back to the client.
On the client, the sample replaces the scriptNode from the previous step with one that sends the data to a socket to be defined later. It then creates that secure Websocket connection to the server. Once both the server and the microphone have connected, it starts listening for messages from the server; then it sends the server the sample rate. When the server echos back the sample rate, the client replaces the listener with the more permanent transcription handler, and connects the scriptNode
to begin streaming audio bytes to the server.
- Navigate to the directory containing
03-websockets
:
cd ~/speaking-with-a-webpage/03-websockets
- Run the application:
mvn clean jetty:run
To access your running webapp, look for the External IP address in your Cloud Console VM Instances page, and point your browser to:
https://<your-external-ip>:8443
Press CTRL+C to stop the server.
Task 6. Transcribe voice to text
The Google Cloud Speech streaming API allows you to send audio bytes to the API in real time and asynchronously receive transcriptions of any speech it detects. The API expects the bytes to be in a specific format, as determined by the configuration that is sent in the beginning of a request. For this webapp, you send the API raw audio samples in the LINEAR16
format - that is, each sample is a 16-bit signed integer - sent at the sample rate obtained by the client.
Sample solution
The 04-speech
subdirectory of the provided speaking-with-a-webpage
repository fills out the server code from the 03-websockets
step. It incorporates the code from the StreamingRecognizeClient sample code above to connect with, pass along audio bytes to, and receive transcripts from the Cloud Speech API. When it asynchronously receives the transcripts, it uses its connection to the Javascript client to pass those along. The Javascript client simply outputs it to the web page.
- Start the application:
cd ~/speaking-with-a-webpage/04-speech
mvn clean jetty:run
- To access your running webapp, look for the External IP address in your Cloud Console VM Instances page, and point your browser to:
https://<your-external-ip>:8443
Task 7. Test your understanding
Below are multiple-choice questions to reinforce your understanding of this lab's concepts. Answer them to the best of your abilities.
Which one of the following protocol-port combinations is responsible for allowing HTTP traffic?
icmp
tcp:80
http:80
tcp:443
What does the Cloud Speech API do?
Provides dynamic transcriptions, sentiment analysis of the transcript content, and data on transcript readers.
Transcribes a voice recording and creates a voice recording from text.
Modeling dynamic transcriptions to the client.
Collects data to use for Machine Learning modeling
What allows the client and the server to communicate with each other?
Websocket
Compute Engine configuration
Web Audio API
Workspace project roles
Solution of Lab
export ZONE=
curl -LO raw.githubusercontent.com/Techcps/GSP-Short-Trick/master/Speaking%20with%20a%20Webpage%20-%20Streaming%20Speech%20Transcripts/techcps.sh
sudo chmod +x techcps.sh
./techcps.sh
Press CTRL+C to stop the server when you see this kind of output:
Check your progress on task 1-3 && do not run the next command until you get the score
curl -LO raw.githubusercontent.com/Techcps/GSP-Short-Trick/master/Speaking%20with%20a%20Webpage%20-%20Streaming%20Speech%20Transcripts/techcps1.sh
sudo chmod +x techcps1.sh
./techcps1.sh