JavaScript:Web Speech API 入門

Web Speech API のサンプルプログラムです。ブラウザは Chrome をご利用ください。

webspeech.html

<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Web Speech API</title>
</head>
<body>
<style>
#Checkbox[type="checkbox"] {
  display:none;
}
#Checkbox + label:before {
  color:gray;
  content:"\25c9";
  cursor:pointer;
  font-size:20pt;
  vertical-align:middle;
}
#Checkbox:checked + label:before {
  color:red;
  content:"\25c9";
}
</style>
<span style="font-size:50pt; letter-spacing:-56.7px; vertical-align:middle;">&#x1f3a4;</span>
<input id="Checkbox" type="checkbox"><label for="Checkbox">&nbsp;&larr;&nbsp;<span style="color:red;">ON</span>/<span style="color:gray;">OFF</span></label>
<output id="Output"></output>
<script>
const SpeechRecognition = webkitSpeechRecognition || SpeechRecognition;
const speechRecognition = new SpeechRecognition();
speechRecognition.lang = "ja-jp";
const checkbox = document.getElementById("Checkbox");
const handleOnCheckUncheck = () => checkbox.checked === true ? speechRecognition.start() : speechRecognition.stop();
checkbox.onchange = handleOnCheckUncheck;
speechRecognition.onend = handleOnCheckUncheck;
speechRecognition.onresult = () => document.getElementById("Output").innerHTML = event.results[0][0].transcript;
</script>
</body>
</html>
 

 

webspeech.js(Node.js)

/* server
cd /d d:\webspeech
npm install express
node webspeech.js
*/
/* client
http://localhost:8080/webspeech.html
*/
const host = "127.0.0.1";
const port = 8080;
const webapp = require("express")();
webapp.get("/:file", (request, response) => response.sendFile(__dirname + "/public/" + request.params.file));
webapp.listen(port, host, console.log(`Web server running at http://${host}:${port}/`));
 

 

〈ファイルの配置〉

D:\webspeech\webspeech.js
D:\webspeech\public\webspeech.html


参考記事