Last active
December 9, 2018 10:40
-
-
Save ksoda/33f005e64e5987a7bf853856f090f685 to your computer and use it in GitHub Desktop.
Echo using Web Speech API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
"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> | |
`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Google Chrome Version 70.0.3538.77 (Official Build) (64-bit)