How to Add Speech Recognition to the Website – JavaScript

With the use of Speech Recognition API, you can enable the web browser to take speech input on the page and convert it into text.

For accessing this on the page need to allow microphone access by the user.

In this tutorial, I am creating an example where allowing the users to search posts by speech. On the basis of speech recognition display response on the screen using jQuery AJAX.

How to Add Speech Recognition to the Website – JavaScript


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. CSS
  5. PHP
  6. Script
  7. Demo
  8. Conclusion

1. Table structure

I am using posts table in the tutorial example.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create a textbox to display the words user said and a button to enable speech recognition.

Display search response in <div class='container'> using jQuery AJAX.

Completed Code

<div class='search_container'>
  <!-- Search box-->
  <input type='text' id='speechText' > &nbsp; 
  <input type='button' id='start' value='Start' onclick='startRecording();'>
</div>

<!-- Search Result -->
<div class="container"></div>

4. CSS

.search_container{
  margin: 0 auto;
  width: 55%;
}

.search_container #speechText{
  width: 80%;
  padding-top: 5px;
  padding-bottom: 5px;
}

.search_container #start{
  padding-top: 5px;
  padding-bottom: 5px;
}

.container{
  width: 55%;
  margin: 0 auto;
  border: 0px solid black;
  padding: 10px 0px;
}

/* post */
.post{
  width: 97%;
  min-height: 200px;
  padding: 5px;
  border: 1px solid gray;
  margin-bottom: 15px;
}

.post h1{
  letter-spacing: 1px;
  font-weight: normal;
  font-family: sans-serif;
}


.post p{
  letter-spacing: 1px;
  text-overflow: ellipsis;
  line-height: 25px;
}

/* more link */
.more{
  color: blue;
  text-decoration: none;
  letter-spacing: 1px;
  font-size: 16px;
}

5. PHP

Create a getData.php file.

Search the POST value on the posts table – title, content, and link fields.

Read fetched records and create HTML string. Return the $html.

Completed Code

<?php

include 'config.php';

$searchText = $_POST['speechText'];

// search query
$query = 'SELECT * FROM posts_1 WHERE title like "%'.$searchText.'%" or content like "%'.$searchText.'%" or link like "%'.$searchText.'%"';

$result = mysqli_query($con,$query);

$html = '';
if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_array($result)){
    $id = $row['id'];
    $title = $row['title'];
    $content = $row['content'];
    $shortcontent = substr($content, 0, 160)."...";
    $link = $row['link'];

    // Creating HTML structure
    $html .= '<div id="post_'.$id.'" class="post">';
    $html .= '<h1>'.$title.'</h1>';
    $html .= '<p>'.$shortcontent.'</p>';
    $html .= '<a href="'.$link.'" class="more" target="_blank">More</a>';
    $html .= '</div>';

  }
}else{
  $html .= '<div >';
  $html .= '<p>No Record Found.</p>';
  $html .= '</div>';
}

echo $html;
exit;

6. Script

Create an Object of webkitSpeechRecognition Class.

Start Recording –

The startRecording() function call on Start button click. From the function call recognition.start() method.

If the microphone access not allowed on the page then browser ask the use of the microphone.

How to Add Speech Recognition to the Website – JavaScript

The user can allow or block it. If allowed then the browser can take input from the microphone.


Read Speech input –

The recognition.onresult function is called after recognition the said text.

Get the speech text and assign in the search box element.

Pass the saidText in the searchPosts() function to fetch records using AJAX.


Fetch Records –

From searchPosts() method send an AJAX request and on successful callback append the response in $('.container').

Complete Code

var recognition = new webkitSpeechRecognition();

recognition.onresult = function(event) { 
  var saidText = "";
  for (var i = event.resultIndex; i < event.results.length; i++) {
    if (event.results[i].isFinal) {
      saidText = event.results[i][0].transcript;
    } else {
      saidText += event.results[i][0].transcript;
    }
  }
  // Update Textbox value
  document.getElementById('speechText').value = saidText;
 
  // Search Posts
  searchPosts(saidText);
}

function startRecording(){
  recognition.start();
}

// Search Posts
function searchPosts(saidText){

  $.ajax({
    url: 'getData.php',
    type: 'post',
    data: {speechText: saidText},
    success: function(response){
       $('.container').empty();
       $('.container').append(response);
    }
  });
}

7. Demo

View Demo


8. Conclusion

The user can enable and disable microphone access on the page whenever wants and it is only working on those web browsers which supports webkitSpeechRecognition API.

I tested on the following browsers –

Browser webkitSpeechRecognition API Support
Chrome Yes
Edge Yes
Opera No
Firefox No
Safari No
IE No
If you found this tutorial helpful then don't forget to share.

8 thoughts on “How to Add Speech Recognition to the Website – JavaScript”

  1. Greeting Makitweb….

    Great script It works on the demopage perfect with browser from google
    but in my server XAMPP + google browser I don`t get alloud function
    for using microphone.

    When I try to open manual the microphone function on my browser-config from google it is also not working.

    Hope you have any clu how to solve it ????

    your sincerely

    Jan Molendijk (Holland)

    Reply

Leave a Comment