| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API | [Back] [Original] |
Get to know MDN better
macOS Dictation Windows Copilot
Speech color changer /HTML
<h1>Speech color changer</h1>
<p class="hints"></p>
<button>Start recognition</button>
<p class="output"><em>...diagnostic messages</em></p>
CSS
JavaScript
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const SpeechRecognitionEvent =
window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent;
const colors = [
"aqua",
"azure",
"beige",
"bisque",
"black",
"blue",
"brown",
"chocolate",
"coral",
//
];
const recognition = new SpeechRecognition();
SpeechRecognition.continuous: (true) (false) SpeechRecognition.lang: SpeechRecognition.interimResults: SpeechRecognition.maxAlternatives: 1 recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;
<html> <button> onclick SpeechRecognition.start() forEach()
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
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
SpeechRecognitionEvent.results SpeechRecognitionResult SpeechRecognitionResultList [0] 0 SpeechRecognitionResult SpeechRecognitionResult SpeechRecognitionAlternative 2 [0] 0 SpeechRecognitionAlternative SpeechRecognitionAlternative transcript UI 1 speechend SpeechRecognition.stop()
recognition.onspeechend = () => {
recognition.stop();
};
2 nomatch
recognition.onnomatch = (event) => {
diagnostic.textContent = "I didn't recognize that color.";
};
error SpeechRecognitionErrorEvent.error
recognition.onerror = (event) => {
diagnostic.textContent = `Error occurred in recognition: ${event.error}`;
};
API1
On-device speech color changer
SpeechRecognition.processLocally true false
recognition.processLocally = true;
processLocally = true start() language-not-supported
2
(<button>) click
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()
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"
const phraseData = [
{ phrase: "azure", boost: 5.0 },
{ phrase: "khaki", boost: 3.0 },
{ phrase: "tan", boost: 2.0 },
];
SpeechRecognitionPhrase ObservableArray SpeechRecognitionPhrase() SpeechRecognitionPhrase
const phraseObjects = phraseData.map(
(p) => new SpeechRecognitionPhrase(p.phrase, p.boost),
);
SpeechRecognition phraseObjects SpeechRecognition.phrases
recognition.phrases = phraseObjects;
JavaScript push
recognition.phrases.push(new SpeechRecognitionPhrase("thistle", 5.0));
( text-to-speech TTS)
API SpeechSynthesis OS API
Speech synthesizer Enter/Return Play
HTML CSS <select> JavaScript <option>
<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
UI DOM Window.speechSynthesis API SpeechSynthesis
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> populateVoiceList() SpeechSynthesis.getVoices() SpeechSynthesisVoice <option> SpeechSynthesisVoice.name SpeechSynthesisVoice.lang -- DEFAULT SpeechSynthesisVoice.default true
option data- option select
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
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
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
pitch.onchange = () => {
pitchValue.textContent = pitch.value;
};
rate.onchange = () => {
rateValue.textContent = rate.value;
};
SpeechGrammarSpeechGrammarListSpeechRecognitionSpeechRecognitionAlternativeSpeechRecognitionErrorEventSpeechRecognitionEventSpeechRecognitionPhraseSpeechRecognitionResultSpeechRecognitionResultListSpeechSynthesisSpeechSynthesisErrorEventSpeechSynthesisEventSpeechSynthesisUtteranceSpeechSynthesisVoice| Web Proxy Viewer | New URL | Original Page |