How to Build a Voice-Powered AI Application with the Web Speech API


The Web Speech API is a web browser API that enables web applications to use sound as data in their operations. With the API, web apps can transcribe the speech in sound input and also synthesise speech from text.

This guide shows you how to build a full-stack web application that:

  • Accepts audio input and transcribes the speech in it

  • Prompts an AI agent with the transcription

  • Displays the AI response on the UI

The application you’ll build will be a simplified version of the Use Voice feature on AI chat applications highlighted in the image below:

Use voice feature of AI chat applications

By practising along with this article, you’ll learn how to:

  • Build a frontend application that uses the SpeechRecognition API to accept voice input and transcribe it

  • Build a backend app that prompts an AI assistant of your choice and sends a response back to clients

  • Connect both applications together to send the transcription to the backend as a prompt and display the AI response on the frontend

Optionally, you’ll also learn how to host the frontend with Firebase and the backend with Google Cloud Run.

Table of Contents

Prerequisites

This guide assumes that you have a working knowledge of HTML, CSS, and JavaScript in the browser. Basic familiarity with Node.js is beneficial but not essential.

In addition, you should have:

  • Google Chrome (at least version 33 ) and a functional audio input device

  • Node.js and npm installed on your computer

  • An API key from any AI assistant of your choice

  • A Google Cloud account and a Firebase account if you intend to deploy the applications

The Web Speech API

The Web Speech API enables applications to transcribe the speech in audio input and also synthesise audio from text. The API is made up of two components:

  • The SpeechRecognition component which receives audio input, recognises speech in the input and transcribes it

  • The SpeechSynthesis component which synthesises speech from text

You’ll use the SpeechRecognition component in this guide.

How the SpeechRecognition Component Works

The SpeechRecognition component works through a JavaScript object instantiated in code.

const recognition = new SpeechRecognition();

The recognition instance exposes several event listeners that respond to audio input. For example, the audiostart event fires when sound is first detected, logging "audio detected" to the console as shown in the snippet below.

recognition.addEventListener("audiostart", function(event){
  console.log("audio detected")
}

The first time it recognises speech in a sound byte, the speechstart event is fired.

A SpeechRecognition instance also has the ability to configure how speech recognition should work. For example, it has a property called lang which sets the language that it should recognise. The default value of the lang property is the HTML lang attribute value, or the browser’s language setting. It also has a boolean property called interimResults, which when set to true, enables the instance to return transcriptions incrementally rather than waiting for the audio input to end.

From speech to transcription

Audio captured by the microphone is processed by a recognition engine which could be in a remote server (for Google Chrome) or embedded in the browser (for Firefox).

After processing, the recognition engine returns a result, which is a list of words or phrases that have been recognised in the speech.

Each transcription in the list has two properties: confidence, a numerical estimate of its accuracy ranging from 0 (low) to 1 (high), and transcript, the recognised text for all or part of the speech.

How the Application Works

In order for a SpeechRecognition instance to capture audio, it needs access to the microphone. The browser requests for permission to use the microphone and, if granted, the application uses it to capture audio for the instance.

Diagram of how the application works

Speech captured by the instance goes through the recognition engine and produces results or transcriptions. Results with high confidence are combined and sent to the backend via an API request.

The backend uses the transcript it receives to prompt an AI assistant. The response from the AI assistant is sent back to the frontend and displayed on the UI as shown in the screenshot below:

User interface of prompt AI with the web speech API application

How to Build the Application

First, you’ll build a Node.js backend application that:

  • Receives text prompt from the frontend

  • Sends the prompt to an AI assistant and receives a response

  • Returns the response of the AI assistant to the frontend

Next, you’ll build the frontend to:

  • Accept your speech prompt, transcribe it, and display the transcription

  • Send the transcription result to the backend

  • Receive, format and display the response from the backend

Optionally, you’ll deploy the frontend to Firebase and the backend to Google Cloud Run, connecting them so the application is publicly accessible.

Create the Backend Application with Node.js

The backend application you’ll build in this section will receive text prompt from clients and use it to prompt an AI assistant. After receiving a response from the AI assistant, it will send the response back to the client.

We’ll use Gemini in this guide, but you can use any AI assistant of your choice.

  1. Create a folder for the backend app and give it a name, for example, “server”.

  2. In terminal, navigate to the project folder, run the npm init command, and answer the follow-up questions to generate a package.json file

  3. In the root of the project, create a file named index.js.

Your project folder should have a structure like this:

├── index.js
├── package.json

The package.json file should have the following values for main , type and scripts.start:

 { 
    "main": "index.js", 
    "type": "module", 
    "scripts": { 
       "start": "node index.js" 
    }, 
}  
  1. Copy and paste the code below into the index.js file to set up the server:
import http from "node:http";

async function parseRequestBody(req) { 
    return new Promise((resolve, reject) => { 
        let data = ""; 
        req.on("data", (chunk) => (data += chunk)); 
        req.on("end", () => resolve(JSON.parse(data))); 
        req.on("error", reject); 
    }); 
}

const server = http.createServer(async function (req, res) { 
    switch (req.method) { 
        case "POST":
          return res.end("POST request received");
        default:
          return res.end("non-POST request received");
    }
})

const port = Number(process.env.PORT) || 8000; 
server.listen(port, function () { 
    console.log(server running on port ${port}); 
});

In the code snippet above, the http module is imported from Node.js. The parseRequestBody function converts the request body stream of a HTTP request to a JavaScript object.

The server is created using the http.createServer method, with the Access-Control-Allow-Origin header set to * to allow requests from any client. It responds with POST request received for POST requests and non-POST request received for all others. By default, it listens on port 8000 unless a PORT environment variable is defined.

Run npm run start to start the server. To confirm it is running, execute the following command in the terminal:

# For Linux/Mac, use:
curl -X POST -H "Content-Type: application/json" -d '{"prompt":"hello"}' http://localhost:8000

# For Windows, use:
curl.exe -X POST -H "Content-Type: application/json" -d '{"prompt":"hello"}' http://localhost:8000

You’ll get the POST request received response from the server.

Integrate an AI Assistant into the Node.js Application

In this section, you’ll integrate the AI assistant into the backend application, prompt it with data sent from the frontend, and return its response to the client. Again, we’ll use Gemini for this here.

Visit the npm page for your chosen AI assistant to learn how to install and set it up. Here are the npm pages for the most popular AI assistants:

Update the index.js file to include the setup for the AI assistant using the snippet below:

import http from "node:http";
import { GoogleGenAI } from "@google/genai"; 

const ai = new GoogleGenAI({ apiKey: "" });

async function parseRequestBody(req) { /* minimised code */ }

const server = http.createServer(async function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");

    switch (req.method) { 
        case "POST":
          const body = await parseRequestBody(req);
          const response = await ai.models.generateContent({
            model: "gemini-2.5-flash", // or whatever model you have
            contents: body.prompt,
         });

         return res.end(response.text);

        default:
          return res.end("non-POST request received");
    }
}
/* previous code minimised*/

The GEMINI_API_KEY is retrieved from the environment variables and passed as the apiKey to GoogleGenAI, which initialises the AI assistant.

The POST request body is parsed into a JavaScript object, and body.prompt is passed to ai.models.generateContent to prompt the AI assistant. The text property of the response which is in Markdown format, is then returned to the client.

Restart the server and test the current setup by making an API request to it with curl using the snippet below:

# For Linux/Mac:

curl -X POST -H "Content-Type: application/json" -d '{"prompt":"hello"}' http://localhost:8000

# For Windows:

curl.exe -X POST -H "Content-Type: application/json" -d '{"prompt":"hello"}' http://localhost:8000

You’ll get an AI text response in the form of Markdown.

Create the Frontend Application with Vite

Vite is a build tool that provides a faster and more seamless development experience for developing applications. You’ll use Vite to create the frontend application and connect it with the backend application from the previous section.

In another folder, create a project with Vite by running the npm create vite@latest command and answer the prompts:

npm create vite@latest

Need to install the following packages:
create-vite@8.1.0
Ok to proceed? (y) y

> npx create-vite

◇  Project name:
│  [name-of-your-frontend-app] e.g prompt-ai-with-speech-frontend
│
◇  Select a framework:
│  Vanilla
│
◇  Select a variant:
│  JavaScript
│
◇  Use rolldown-vite (Experimental)?:
│  No
│
◇  Install with npm and start now?
│  Yes

Open the project created in your code editor and make the following updates:

  1. Replace the content of index.html with the code snippet below:


  
    
    
    Prompt AI with the Web Speech Recognition API
  
  
    

Scroll to Top