[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API [Back]  [Original]

Web Speech API - API | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Web Speech API

Web Speech API 2 . . .

In this article

, , . SpeechGrammar, , . JSpeech Grammar Format(JSGF.).

, , ( ) , .

: Chrome - . - , -.

Speech color changer. , .

   Speech Color changer.         ,        .      . [ Speech Color changer. , . .]

(, Chrome).

HTML CSS

. , , , , , , , .

CSS ,

JavaScript

.

Chrome

, Chrome , Chrome Firefox.

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const SpeechGrammarList = window.SpeechGrammarList || window.webkitSpeechGrammarList;
const SpeechRecognitionEvent = window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent;

, , .

:

const colors = {
  : 'red',
  : 'orange',
  : 'yellow',
  : 'green',
  : 'blue',
  : 'darkblue',
  : 'violet'
};

const colorsList = Object.keys(colors);

const grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colorsList.join(' | ') + ' ;';

    -  JSpeech Grammar Format (JSGF) -       .

:

  • , JavaScript.
  • - #JSGF V1.0; - . .
  • , . public , , (), , , - , . , ("|" - "pipe character").
  • , , , . .

, , .

SpeechRecognition(). , , SpeechGrammarList().

const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();

"" , SpeechGrammarList.addFromString(). , , , ( 0 1 ). SpeechGrammar.

js
speechRecognitionList.addFromString(grammar, 1);

SpeechGrammarList , SpeechRecognition.grammars. , :

js
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "ru-RU";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

: SpeechRecognition.continuous , 1 , , . , Gecko.

, .

DOM-, , onclick, . SpeechRecognition.start().

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

recognition.onaudiostart = function() {
  microphoneWrapper.style.visibility = 'hidden';
  audioRecordAnimation.style.visibility = 'visible';
};

, , , (. SpeechRecognition.) , , , , SpeechRecognition.onresult, . getColor()

function getColor(speechResult) {
  for (let index = 0; index < colorsList.length; index += 1) {
    if (speechResult.indexOf(colorsList[index]) !== -1) {
      const colorKey = colorsList[index];
      return [colorKey, colors[colorKey]];
    }
  }
  return null;
}

recognition.onresult = function(event) {
  const last = event.results.length - 1;
  const colors = getColor(event.results[last][0].transcript);
  recognitionTextResult.textContent = ': ' + colors[0];
  speechRecognitionSection.style.backgroundColor = colors[1];
  console.log('Confidence: ' + event.results[0][0].confidence);
};

, . SpeechRecognitionEvent.results SpeechRecognitionResultList, SpeechRecognitionResult. , , last SpeechRecognitionResult . SpeechRecognitionResult SpeechRecognitionAlternative, . , , , [0] SpeechRecognitionAlternative 0. , , .

SpeechRecognition.speechend, ( SpeechRecognition.stop() ), , .

recognition.onspeechend = function() {
  recognition.stop();
  microphoneWrapper.style.visibility = 'visible';
  audioRecordAnimation.style.visibility = 'hidden';
};

: . , SpeechRecognition.onnomatch, , , Firefox Chrome, , :

recognition.onnomatch = function(event) {
  alert("I didn't recognise that color.");
};

SpeechRecognition.onerror , . SpeechRecognitionError.error :

recognition.onerror = function(event) {
  alert(`Error occurred in recognition: ${event.error}`);
};

(text-to-speech tts) .

Web Speech API - SpeechSynthesis - (utterances - ""), , "", . . , , API .

Speak easy synthesis. , , , , . Enter/Return, .

   Speak easy synthesis.       ,        ,         . [ Speak easy synthesis. , , .]

.

HTML CSS

HTML CSS . . <select> , <option> JavaScript (. ).

CSS ,

<section>
  <h1> </h1>
  <p>        "Play",   .      </p>

  <form>
    <input type="text" class="text">
    <div class="row">
      <div class="values-box">
        <div class="value-box">
          <div> (Rate)</div>
          <div class="value value--rate-value">1</div>
        </div>

        <div class="value-box">
          <div> (Pitch)</div>
          <div class="value value--pitch-value">1</div>
        </div>
      </div>

      <div class="ranges-box">
        <input type="range" min="0.5" max="2" value="1" step="0.1" id="rate">
        <input type="range" min="0" max="2" value="1" step="0.1" id="pitch">
      </div>
    </div>

    <select>
    </select>

    <button id="play" type="submit">Play</button>

  </form>

JavaScript

, .

, DOM-.

API - window.speechSynthesis, SpeechSynthesis, .

const synth = window.speechSynthesis;
const inputForm = document.querySelector('form');
const inputTxt = document.querySelector('.text');
const voicesList = document.querySelector('select');
const pitch = document.querySelector('#pitch');
const pitchValue = document.querySelector('.value--pitch-value');
const rate = document.querySelector('#rate');
const rateValue = document.querySelector('.value--rate-value');
let voices = [];

<select> , , populateVoiceList(). SpeechSynthesis.getVoices(), , SpeechSynthesisVoice. , <option> , , ( SpeechSynthesisVoice.name), ( SpeechSynthesisVoice.lang), " ", (, SpeechSynthesisVoice.default true.)

data- , , , (<select>).

function populateVoiceList() {
  voices = synth.getVoices();
  const selectedIndex =
  voicesList.selectedIndex < 0 ? 0 : voicesList.selectedIndex;
  voicesList.innerHTML = '';

  for(i = 0; i < voices.length ; i++) {
    const option = document.createElement('option');
    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';

    if(voices[i].default) {
      option.textContent += ' -- DEFAULT';
    }

    option.setAttribute('data-lang', voices[i].lang);
    option.setAttribute('data-name', voices[i].name);
    voiceSelect.appendChild(option);
  }
  voicesList.selectedIndex = selectedIndex;
}

, . , Firefox SpeechSynthesis.onvoiceschanged SpeechSynthesis.getVoices(). , Chrome , , , if .

populateVoiceList();
  if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

, "" , , Enter/Return Play. onsubmit html-. - speak() SpeechSynthesisUtterance(), .

, . HTMLSelectElement selectedOptions <option>, data-name, SpeechSynthesisVoice, . "" SpeechSynthesisUtterance.voice.

, SpeechSynthesisUtterance.pitch ( ) SpeechSynthesisUtterance.rate () . , , , SpeechSynthesis.speak(), SpeechSynthesisUtterance .

speak() , , SpeechSynthesis.speaking , SpeechSynthesis.cancel() .

SpeechSynthesisUtterance.onpause, SpeechSynthesisEvent . SpeechSynthesis.pause() , .

, blur() . , , , Firefox.

js
function speak() {
  if (synth.speaking) {
    console.error("speechSynthesis.speaking");
    synth.cancel();
    setTimeout(speak, 300);
  } else if (inputTxt.value !== "") {
    const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
    utterThis.onend = function (event) {
      console.log("SpeechSynthesisUtterance.onend");
    };

    utterThis.onerror = function (event) {
      console.error("SpeechSynthesisUtterance.onerror");
    };
    const selectedOption =
      voicesList.selectedOptions[0].getAttribute("data-name");

    for (i = 0; i < voices.length; i++) {
      if (voices[i].name === selectedOption) {
        utterThis.voice = voices[i];
      }
    }

    utterThis.onpause = function (event) {
      const char = event.utterance.text.charAt(event.charIndex);
      console.log(
        "Speech paused at character " +
          event.charIndex +
          ' of "' +
          event.utterance.text +
          '", which is "' +
          char +
          '".',
      );
    };

    utterThis.pitch = pitch.value;
    utterThis.rate = rate.value;
    synth.speak(utterThis);
  }
}

inputForm.onsubmit = function (event) {
  event.preventDefault();
  speak();
  inputTxt.blur();
};

/, , , .

js
pitch.onchange = function () {
  pitchValue.textContent = pitch.value;
};

rate.onchange = function () {
  rateValue.textContent = rate.value;
};

Web Proxy Viewer  |  New URL  |  Original Page