Speech Recognition API in JS

The original link

Introduction to the

There are actually two kinds of HTML5 apis for Web Speech. One is “Speech Recognition” and the other is “Speech Synthesis”. These two terms sound fancy, but they actually refer to “Speech to text” respectively. “And” Text to speech “.

This article is about Speech Recognition. Please move on to another article on Speech Synthesis.

SpeechRecognition uses the SpeechRecognition API, currently only supported by Chrome, with a webkit prefix.

  • Create a new instance of SpeechRecognition
var recognition = new webkitSpeechRecognition();
Copy the code
  • Set whether to keep listening or turn off reception after hearing a sound.
recognition.continuous = true;
Copy the code
  • Set whether temporary results are allowed, which is an intermediate process of recognition, and return isFinal = false.
recognition.interimResults = true;
Copy the code
  • Set the language
recognition.lang = 'cmn-Hans-CN'; // Mandarin (mainland China)Copy the code
  • To control the start and stop of speech recognition, start() and stop() methods can be used, corresponding to onstart and onend events respectively
/ / open recognition. The start (); / / stop recognition. Stop ();Copy the code
  • To process the identified result, you can use some event methods, such as onResult:
recognition.onresult = function(event) { 
    console.log(event);
}
Copy the code

Event returns the format of the result

{results: {0: {0: {confidence: 0.695017397403717, transcript: "Hello, world"}, isFinal:true, length:1}, length:1},}Copy the code
  • Error handling
recognition.onerror = function(event) { 
    console.log(event);
}
Copy the code

Have a try

Google code:

Simple test of PC and mobile terminal, PC only Chrome support, mobile all failed… 😂

The resources

  • Introduction to HTML5 Speech Synthesis API
  • SpeechRecognition