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

API - Web API | MDN

MDN Web Docs

View in English Always switch to English

API

API text to speech TTS 2

API SpeechRecognition

macOS Dictation Windows Copilot

Speech color changer /HTML

Speech Color changer  UI [Speech Color changer UI]

URL

HTML CSS

HTML CSS (<p>) (<button>)

html
<h1>Speech color changer</h1>

<p class="hints"></p>

<button>Start recognition</button>

<p class="output"><em>...diagnostic messages</em></p>

CSS

JavaScript

JavaScript

js
const SpeechRecognition =
  window.SpeechRecognition || window.webkitSpeechRecognition;
const SpeechRecognitionEvent =
  window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent;

js
const colors = [
  "aqua",
  "azure",
  "beige",
  "bisque",
  "black",
  "blue",
  "brown",
  "chocolate",
  "coral",
  // 
];

SpeechRecognition()

js
const recognition = new SpeechRecognition();

js
recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

<html> <button> onclick SpeechRecognition.start() forEach()

js
const diagnostic = document.querySelector(".output");
const bg = document.querySelector("html");
const hints = document.querySelector(".hints");
const startBtn = document.querySelector("button");

const colorHTML = colors
  .map((v) => `<span >${v}</span>`)
  .join("");
hints.innerHTML = `Press the button then say a color to change the background color of the app. Try ${colorHTML}.`;

startBtn.onclick = () => {
  recognition.start();
  console.log("Ready to receive a color command.");
};

SpeechRecognition result

js
recognition.onresult = (event) => {
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
  console.log(`Confidence: ${event.results[0][0].confidence}`);
};

2

1 speechend SpeechRecognition.stop()

js
recognition.onspeechend = () => {
  recognition.stop();
};

2 nomatch

js
recognition.onnomatch = (event) => {
  diagnostic.textContent = "I didn't recognize that color.";
};

error SpeechRecognitionErrorEvent.error

js
recognition.onerror = (event) => {
  diagnostic.textContent = `Error occurred in recognition: ${event.error}`;
};

API1

On-device speech color changer

: API

SpeechRecognition.processLocally true false

js
recognition.processLocally = true;

processLocally = true start() language-not-supported

2

  1. SpeechRecognition.available()
  2. SpeechRecognition.install()

(<button>) click

js
startBtn.addEventListener("click", () => {
  // 
  SpeechRecognition.available({ langs: ["en-US"], processLocally: true }).then(
    (result) => {
      if (result === "unavailable") {
        diagnostic.textContent = `en-US is not available to download at this time. Sorry!`;
      } else if (result === "available") {
        recognition.start();
        console.log("Ready to receive a color command.");
      } else {
        diagnostic.textContent = `en-US language pack is downloading...`;
        SpeechRecognition.install({
          langs: ["en-US"],
          processLocally: true,
        }).then((result) => {
          if (result) {
            diagnostic.textContent = `en-US language pack downloaded. Start recognition again.`;
          } else {
            diagnostic.textContent = `en-US language pack failed to download. Try again later.`;
          }
        });
      }
    },
  );
});

available() 2

  • langs
  • true processLocallyfalse

Promise 3

  • unavailable
  • unavailable
  • downloadable downloading install()

install() available() langs langs true false Promise

available() install() on-device-speech-recognition Permissions-Policy

on-device-speech-recognition self

available() install() quality

quality dictation available() unavailable SpeechRecognition processLocally false API start()

available start() quality dictation install()

js
startBtn.addEventListener("click", () => {
  // 
  SpeechRecognition.available({
    langs: ["en-US"],
    processLocally: true,
    quality: "dictation",
  }).then((result) => {
    if (result === "unavailable") {
      diagnostic.textContent = `On-device recognition for dictation not available, running with cloud recognition`;
      recognition.processLocally = false;
      recognition.start();
    } else if (result === "available") {
      recognition.start();
      console.log("Ready to receive a color command.");
    } else {
      diagnostic.textContent = `en-US language pack downloading`;
      SpeechRecognition.install({
        langs: ["en-US"],
        processLocally: true,
        quality: "dictation",
      }).then((result) => {
        if (result) {
          diagnostic.textContent = `en-US language pack downloaded. Try again.`;
        } else {
          diagnostic.textContent = `en-US language pack failed to download. Try again later.`;
        }
      });
    }
  });
});

On-device speech color changer azure "as you" khaki ("car key")tanthistle ("this all")

API

SpeechRecognitionPhrase SpeechRecognition.phrases SpeechRecognitionPhrase

  • phrase
  • boost 0.0 10.0

"On-device speech color changer"

js
const phraseData = [
  { phrase: "azure", boost: 5.0 },
  { phrase: "khaki", boost: 3.0 },
  { phrase: "tan", boost: 2.0 },
];

SpeechRecognitionPhrase ObservableArray SpeechRecognitionPhrase() SpeechRecognitionPhrase

js
const phraseObjects = phraseData.map(
  (p) => new SpeechRecognitionPhrase(p.phrase, p.boost),
);

SpeechRecognition phraseObjects SpeechRecognition.phrases

js
recognition.phrases = phraseObjects;

JavaScript push

js
recognition.phrases.push(new SpeechRecognitionPhrase("thistle", 5.0));

( text-to-speech TTS)

API SpeechSynthesis OS API

Speech synthesizer Enter/Return Play

speak easy synthesis  UI [speak easy synthesis UI]

URL

HTML CSS

HTML CSS <select> JavaScript <option>

html
<h1>Speech synthesizer</h1>

<p>
  Enter some text in the input below and press return to hear it. Change voices
  using the dropdown menu.
</p>

<form>
  <input type="text" class="txt" />
  <div>
    <label for="rate">Rate</label
    ><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate" />
    <div class="rate-value">1</div>
    <div class="clearfix"></div>
  </div>
  <div>
    <label for="pitch">Pitch</label
    ><input type="range" min="0" max="2" value="1" step="0.1" id="pitch" />
    <div class="pitch-value">1</div>
    <div class="clearfix"></div>
  </div>
  <select></select>
</form>

JavaScript

JavaScript

UI DOM Window.speechSynthesis API SpeechSynthesis

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector(".txt");
const voiceSelect = document.querySelector("select");

const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector(".pitch-value");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector(".rate-value");

const voices = [];

select

<select> populateVoiceList() SpeechSynthesis.getVoices() SpeechSynthesisVoice <option> SpeechSynthesisVoice.name SpeechSynthesisVoice.lang -- DEFAULT SpeechSynthesisVoice.default true

option data- option select

js
function populateVoiceList() {
  voices = synth.getVoices();

  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;

    if (voice.default) {
      option.textContent += "  DEFAULT";
    }

    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
}

voiceschanged SpeechSynthesis.getVoices() Chrome

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

Enter/Return onsubmit SpeechSynthesisUtterance()

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

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

js
inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);
  utterThis.onpause = (event) => {
    const char = event.utterance.text.charAt(event.charIndex);
    console.log(
      `Speech paused at character ${event.charIndex} of "${event.utterance.text}", which is "${char}".`,
    );
  };
  inputTxt.blur();
};

pause SpeechSynthesisEvent SpeechSynthesis.pause()

blur() Firefox OS

UI pitch/rate

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

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

Web Proxy Viewer  |  New URL  |  Original Page