Skip to content

Instantly share code, notes, and snippets.

@ksoda
Last active December 9, 2018 10:40
Show Gist options
  • Save ksoda/33f005e64e5987a7bf853856f090f685 to your computer and use it in GitHub Desktop.
Save ksoda/33f005e64e5987a7bf853856f090f685 to your computer and use it in GitHub Desktop.
Echo using Web Speech API
[
"audioend",
"audiostart",
"end",
"error",
"nomatch",
"result",
"soundend",
"soundstart",
"speechend",
"speechstart",
"start"
].forEach(e => {
// recognition.addEventListener(e, console.debug);
});
document.addEventListener("DOMContentLoaded", main);
function main() {
const synth = window.speechSynthesis;
const recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = "ja";
const mainEl = document.querySelector("main");
let last;
recognition.addEventListener("result", v => {
console.log(v.results.length, v.results[0].length);
last = v;
});
recognition.addEventListener("end", v => {
mainEl.querySelector("#listen").innerText = "Listen";
if (!last) return;
const voice = synth.getVoices().find(x => x.lang === "ja-JP");
const utter = new SpeechSynthesisUtterance(last.results[0][0].transcript);
utter.voice = voice;
synth.speak(utter);
});
let stateListening = false;
mainEl.innerHTML = Button("Listen");
document.querySelector("#listen").addEventListener("click", () => {
console.log("click");
if (!stateListening) {
recognition.start();
mainEl.querySelector("#listen").innerText = "Stop";
} else {
recognition.stop();
mainEl.querySelector("#listen").innerText = "Listen";
}
stateListening = !stateListening;
});
}
function Button(text) {
return `
<button id="listen" style="font-size: -webkit-xxx-large">${text}</button>
`;
}
@ksoda
Copy link
Author

ksoda commented Dec 9, 2018

Google Chrome Version 70.0.3538.77 (Official Build) (64-bit)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment