# Speaking with a Webpage - Streaming Speech Transcripts - GSP125

## **Overview**

The [Google Cloud Speech](https://cloud.google.com/speech-to-text) 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.

![Google Cloud Speech diagram.](https://cdn.qwiklabs.com/%2BtmPWRDLJRkcPZrfu2rrPDz8U9pcVQmycwDIrYyz1js%3D align="left")

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](http://www.eclipse.org/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](http://maven.apache.org/) 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

1. 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
        
2. 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**.
    
3. If necessary, copy the **Username** below and paste it into the **Sign in** dialog.
    
    ```apache
    student-04-99487e535162@qwiklabs.net
    ```
    
    You can also find the Username in the Lab Details pane.
    
4. Click **Next**.
    
5. Copy the **Password** below and paste it into the **Welcome** dialog.
    
    ```apache
    W0HcUVjwxlz5
    ```
    
    You can also find the Password in the Lab Details pane.
    
6. 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.
    
7. 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.

![Navigation menu icon and Search field](https://cdn.qwiklabs.com/9Fk8NYFp3quE9mF%2FilWF6%2FlXY9OUBi3UWtb2Ne4uXNU%3D align="left")

## **Task 1. Create a virtual machine**

[Compute Engine](http://cloud.google.com/compute) 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.

![Compute Engine workflow diagram.](https://cdn.qwiklabs.com/RGXy%2BCuptqMAkO2sDREw8nyXQ4GNMTTzzFGfFKjcwVc%3D align="left")

1. To create a new VM, click the **Navigation menu** () &gt; **Compute Engine** &gt; **VM instances**.
    
2. To create a new instance, click **Create Instance**.
    
3. 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.
        
4. 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**.
            
5. Click **Networking**.
    
    * For **Firewall** check for **Check Allow HTTP traffic** and **Check Allow HTTPS traffic**.
        
6. Click **Security**.
    
    * For **Identity and API access &gt; Service Account** leave as default.
        
    * For **Access scopes** select **Allow full access to all Cloud APIs**.
        
7. 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.

8. Connect to it by clicking the **SSH** button to its right. If prompted, click **Authorize**.
    

![The SSH dropdown button highlighted alongside the speaking-with-a-webpage instance](https://cdn.qwiklabs.com/TE0t3fpHmdOPOH9y9nY6wagSIaCiREOJlgXPYSy9n20%3D align="left")

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](https://cloud.google.com/compute/docs/) reference.

## **Task 2. Download and set up a working example**

1. In the SSH session, install Git and the example here, uses Java 11 and the [Maven](https://maven.apache.org/) project management tool to compile and run its code. Install them on your VM:
    

```apache
sudo apt update && sudo apt install git -y
```

```apache
sudo apt-get install -y maven openjdk-11-jdk
```

**Note:** This command may take a couple of minutes.

2. Clone the working example to your VM:
    

```apache
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 HTTPS
    
* `02-webaudio` - fills out the client-side Javascript to record audio from the client's microphone and display a visualization to confirm it works
    
* `03-websockets` - modifies both the client and the server to communicate with each other through a websocket
    
* `04-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.

3. In order to access this port from your web browser, open your VM's firewall using this [gcloud](https://cloud.google.com/sdk/) command:
    

```apache
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 Jetty
    
* `TranscribeServlet.java` defines the servlet that handles requests to the path `/transcribe`
    

### Running the sample solution

The [01-hello-https](https://github.com/googlecodelabs/speaking-with-a-webpage/tree/master/01-hello-https) subdirectory of the provided `speaking-with-a-webpage` repository contains a Maven [servlet](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/01-hello-https/src/main/java/com/example/flexible/speak/TranscribeServlet.java) project configured for HTTPS. This servlet uses the Jetty servlet framework to serve both [static files](https://github.com/googlecodelabs/speaking-with-a-webpage/tree/master/01-hello-https/src/main/webapp) and a [dynamic endpoint](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/01-hello-https/src/main/java/com/example/flexible/speak/TranscribeServlet.java#L28). It also uses the blog post above to generate a [self-signed certificate](https://github.com/googlecodelabs/speaking-with-a-webpage/tree/master/01-hello-https/src/main/resources) using the Key Tool command, and adds [Jetty configuration](https://github.com/googlecodelabs/speaking-with-a-webpage/tree/master/01-hello-https) to support HTTPS.

1. Start the servlet. Navigate to `01-hello-https.`
    

```apache
cd ~/speaking-with-a-webpage/01-hello-https
```

2. Run the code:
    

```apache
mvn clean jetty:run
```

3. 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](https://console.cloud.google.com/compute/instances) page.

![External IP field highlighted on the Cloud Console VM Instances page.](https://cdn.qwiklabs.com/3xrpjknF9EimX%2Fsx3vWXS0L7KRYF4Xh2quK3Oljs4NI%3D align="left")

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. 😁

![Your connection is not private alert notification.](https://cdn.qwiklabs.com/5OUZbCnfWdVoTEiqDxtVac2NXmrz505fGFossQnVPSI%3D align="left")

### 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](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/02-webaudio/src/main/webapp/javascript/main.js#L150) function to connect the user's microphone to a visualization of the audio. It then adds a [ScriptProcessorNode](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/02-webaudio/src/main/webapp/javascript/main.js#L171) 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](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/02-webaudio/src/main/webapp/javascript/main.js#L177), it retrieves that as well. Start the `02-webaudio` app as follows:

1. Press **CTRL+C** to stop the server.
    
2. Navigate to the directory that contains `02-webaudio`:
    

```apache
cd ~/speaking-with-a-webpage/02-webaudio
```

3. Run the application:
    

```apache
mvn clean jetty:run
```

4. To access your running webapp, look for the **External IP** address in your [Cloud Console VM Instances](https://console.cloud.google.com/compute/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

5. 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](https://en.wikipedia.org/wiki/WebSocket) 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](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/03-websockets/src/main/java/com/example/flexible/speak/TranscribeServlet.java) 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](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/03-websockets/src/main/webapp/javascript/main.js#L180) from the previous step with one that sends the data to a socket to be defined later. It then creates that [secure Websocket connection](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/03-websockets/src/main/webapp/javascript/main.js#L188) 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.

1. Navigate to the directory containing `03-websockets`:
    

```apache
cd ~/speaking-with-a-webpage/03-websockets
```

2. Run the application:
    

```apache
mvn clean jetty:run
```

3. To access your running webapp, look for the **External IP** address in your [Cloud Console VM Instances](https://console.cloud.google.com/compute/instances) page, and point your browser to: `https://<your-external-ip>:8443`
    
4. Press **CTRL+C** to stop the server.
    

## **Task 6. Transcribe voice to text**

The [Google Cloud Speech](https://cloud.google.com/speech-to-text) 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](https://cloud.google.com/speech/reference/rpc/google.cloud.speech.v1beta1#google.cloud.speech.v1beta1.RecognitionConfig) 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](https://github.com/googleapis/java-speech/blob/master/samples/snippets/src/test/java/com/example/speech/RecognizeIT.java) sample code above to [connect with](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/04-speech/src/main/java/com/example/flexible/speak/TranscribeSocket.java#L78), [pass along](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/04-speech/src/main/java/com/example/flexible/speak/TranscribeSocket.java#L61) audio bytes to, and [receive transcripts](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/04-speech/src/main/java/com/example/flexible/speak/TranscribeSocket.java#L141) from the Cloud Speech API. When it asynchronously receives the transcripts, it uses its connection to the Javascript client to [pass those along](https://github.com/googlecodelabs/speaking-with-a-webpage/blob/master/04-speech/src/main/java/com/example/flexible/speak/TranscribeSocket.java#L150). The Javascript client simply outputs it to the web page.

1. Start the application:
    

```apache
cd ~/speaking-with-a-webpage/04-speech
```

```apache
mvn clean jetty:run
```

2. To access your running webapp, look for the **External IP** address in your [Cloud Console VM Instances](https://console.cloud.google.com/compute/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

### New solution

%[https://youtu.be/Ij3tTpFKmg8] 

**Task 1:**

```apache
curl -LO raw.githubusercontent.com/ePlus-DEV/storage/refs/heads/main/labs/GSP125/task1.sh
source lab.sh
```

Manual

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547156370/e58275a1-0677-42e4-bada-3ea5bd8a14cb.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547167773/f343bcf4-e587-492f-8d66-997b10bd2ad1.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547171415/5d92e824-9328-4d24-84eb-610f932b6d22.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547175399/542cfaa9-2dbd-402d-bd1a-65fb5b3778fd.png align="center")

**Task 2:**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547231043/ce613df3-37ed-4967-91aa-f76a928dd577.png align="center")

```apache
sudo apt update && sudo apt install git -y
sudo apt-get install -y maven openjdk-11-jdk
git clone https://github.com/googlecodelabs/speaking-with-a-webpage.git
gcloud compute firewall-rules create dev-ports \
    --allow=tcp:8443 \
    --source-ranges=0.0.0.0/0
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1756547376197/cacda0d4-3d3a-49f4-9048-ca31fede8192.png align="center")

**Task 3:**

```apache
cd ~/speaking-with-a-webpage/01-hello-https
mvn clean jetty:run
```

Press **CTRL+C** to stop the serve

```apache
cd ~/speaking-with-a-webpage/02-webaudio
mvn clean jetty:run
```

---

### Old Solution

%[https://www.youtube.com/watch?v=CT0mIUJNKD4&ab_channel=Techcps] 

```apache
export ZONE=
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739153617082/279aa06f-06a2-4a2d-b118-785b72aefd81.png align="center")

```apache
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 <mark>CTRL+C</mark> to stop the server when you see this kind of output:**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739153643040/201ef434-2800-4495-be49-ead5c87a887e.png align="center")

**Check your progress on <mark>task 1-3</mark> && do not run the next command until you get the score**

```apache
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
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739153812496/f4a25493-d0e9-487c-9ea6-531cae7dc6f2.png align="center")
