HTML5で、音声認識した結果をテキストにして読み上げる
HTML5で音声認識シリーズ第2弾である。
今回もChrome限定だが、音声認識したテキストを読み上げる方法である。
昨日の「10分でつくれる音声認識」が理解できていれば、3分と掛からんだろう。
Chromeでしかできないし、HTML5は関係なくねという疑問はさておき、
下記を参考にして、Webからテキストを読み上げる方法を知る。
力技とはいえ、たった1行のコードで読み上げるとはさすがGoogle様である。
下記のサンプルコードは、音声認識した結果をオウム返しに読み上げたり、
テキスト部分を取得して読み上げたりする簡単なプログラムである。
"text"という変数をif文で判断させれば、異なる受け答えもしてくれるし、
任意のWebやファイルを開かせることもできるだろう。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Speech Recognizer</title> <script> function speechInput() { var text = document.getElementById("textPart").value; document.getElementById("browserPart").src = "http://translate.google.com/translate_tts?tl=ja&q=" + text; document.getElementById("logPart").innerHTML = text; } function onClick() { var text = document.getElementById("textPart").value; document.getElementById("browserPart").src = "http://translate.google.com/translate_tts?tl=ja&q=" + text; document.getElementById("logPart").innerHTML = text; } </script> </head> <body> <header> <div style="text-align:center"> <input type="text" id="textPart" x-webkit-speech lang="ja" style="font-size:24px" onwebkitspeechchange="speechInput();" /> <button onclick="onClick()">実行</button> <hr> </div> </header> <article> <iframe id="browserPart" src="http://translate.google.com/translate_tts?tl=ja&q=ごきげんよう" width="100%" height="50px"></iframe> <div id="logPart" style="text-align:center"></div> </article> </body> </html>