Gistrec

Example of SpeechRecognition

Sep 7th, 2020 (edited)
1,208
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
  2. var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList
  3.  
  4. var recognition = new SpeechRecognition();
  5. var speechRecognitionList = new SpeechGrammarList();
  6.  
  7. speechRecognitionList.addFromString('#JSGF V1.0;', 1);
  8. recognition.grammars = speechRecognitionList;
  9. recognition.continuous = false;
  10. recognition.lang = 'ru-RU';
  11. recognition.interimResults = false;
  12. recognition.maxAlternatives = 1;
  13.  
  14. function log(msg) {
  15.     var time = new Date();
  16.     time = ("0" + time.getHours()).slice(-2)   + ":" +
  17.            ("0" + time.getMinutes()).slice(-2) + ":" +
  18.            ("0" + time.getSeconds()).slice(-2);
  19.     chrome.tabs.executeScript({
  20.         code: `console.log("[${time}] ${msg}");`
  21.     });
  22. }
  23.  
  24. recognition.onresult = function(event) {
  25.     // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  26.     // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  27.     // It has a getter so it can be accessed like an array
  28.     // The first [0] returns the SpeechRecognitionResult at the last position.
  29.     // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results.
  30.     // These also have getters so they can be accessed like arrays.
  31.     // The second [0] returns the SpeechRecognitionAlternative at position 0.
  32.     // We then return the transcript property of the SpeechRecognitionAlternative object
  33.     var transcript = event.results[0][0].transcript;
  34.     var confidence = event.results[0][0].confidence;
  35.     log(`Пользователь сказал: '${transcript}', точность определения: ${confidence}`);
  36. }
  37.  
  38. recognition.onspeechend = function() {
  39.     log('Запись команды остановлена');
  40.     recognition.stop();
  41. }
  42.    
  43. recognition.onerror = function(event) {
  44.     log(JSON.stringify(event).replace(/\"/g, "'"));
  45.     log('Произошла ошибка во время записи команды');
  46. }
Comments
  • User was banned
Add Comment
Please, Sign In to add comment