how to stop and restart web speech api correctly?
Asked Answered
A

2

11

Does it required to create new instance of SpeechRecognition after each speech?

var recognition = new SpeechRecognition();
recognition.start();

Or just stop() and call the start() func again?

recognition.stop();
recognition.start();
Auberon answered 20/3, 2017 at 4:15 Comment(0)
S
4

Only 1 instance is necessary to interact with the SpeechRecognition object.

You can start the listener with start(). You can stop the listener with stop() or abort().

The abort() method slightly differs from the stop method:

The abort() method of the Web Speech API stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a SpeechRecognitionResult.

Here is the example straight from the docs:

var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

var diagnostic = document.querySelector('.output');
var bg = document.querySelector('html');

document.body.onclick = function() {
  recognition.start();
  console.log('Ready to receive a color command.');
}

abortBtn.onclick = function() {
  recognition.abort();
  console.log('Speech recognition aborted.');
}

recognition.onspeechend = function() {
  recognition.stop();
  console.log('Speech recognition has stopped.');
}

Find out more from the SpeechRecognition docs.

Strawberry answered 31/5, 2017 at 15:56 Comment(0)
A
2

You can pause and then continue the current instance by using:

recognition.abort(); //and then followed by:
recognition.start();

if you want to re-start with new config, for example change the language:

recognition.lang = 'id-ID'; //example to change the language
recognition.stop(); //stop recoginition

//try to give a bit delay and then start again with the same instance
setTimeout(function(){ recognition.start(); }, 400);

I have tested and it worked well.

Andrewandrewes answered 4/8, 2019 at 2:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.