Convert Speech to Text Using Google Apps Script

In this tutorial we are going to experiment with the Web Speech API. It’s a very powerful browser interface that allows you to record human speech and convert it into text. We will also use it to do the opposite – reading out strings in a human-like voice.

Speech to Text using Google Apps Script

The first thing we need to do is check if the user has access to the API and show an appropriate error message. Unfortunately, the speech-to-text API is supported only in Chrome and Firefox (with a flag), so a lot of people will probably see that message.

try {
var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
}
catch(e)   {
   console.error(e);
    $('.no-browser-support').show();
    $('.app').hide();
}

Before we can use the voice recognition, we also have to set up a couple of event handlers. Most of them simply listen for changes in the recognition status:

recognition.onresult = function(event) {

  // event is a SpeechRecognitionEvent object.
  // It holds all the lines we have captured so far. 
  // We only need the current one.
  var current = event.resultIndex;

  // Get a transcript of what was said.
  var transcript = event.results[current][0].transcript;

  // Add the current transcript to the contents of our Note.
  noteContent += transcript;
  noteTextarea.val(noteContent);
}

Before we can use the voice recognition, we also have to set up a couple of event handlers. Most of them simply listen for changes in the recognition status:

recognition.onstart = function() {
   instructions.text('Voice recognition activated. Try speaking into the microphone.');
}

   recognition.onspeechend = function() {
   instructions.text('You were quiet for a while so voice recognition turned itself off.');
}

   recognition.onerror = function(event) {
   if(event.error == 'no-speech') {
      instructions.text('No speech was detected. Try again.');
    };
}

Written By:

Sarmad Gardezi A blog scientist by Mind and a Passionate Blogger by heart. Sarmad is Freelancer, Entrepreneur and Google Apps Scripts Developer from Islamabad, Pakistan.

Subscribe to Email Newsletter