Skip to content

Instantly share code, notes, and snippets.

@ixsiid
Last active September 30, 2018 16:57
Show Gist options
  • Save ixsiid/1a58b19ce053ee66cdaba0d07e257eaa to your computer and use it in GitHub Desktop.
Save ixsiid/1a58b19ce053ee66cdaba0d07e257eaa to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Speech API</title>
<script>
var flag_speech = 0;
function vr_function() {
window.SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
var recognition = new webkitSpeechRecognition();
recognition.lang = 'ja';
recognition.interimResults = true;
recognition.continuous = true;
recognition.onsoundstart = function() {
document.getElementById('status').innerHTML = "認識中";
};
recognition.onnomatch = function() {
document.getElementById('status').innerHTML = "もう一度試してください";
};
recognition.onerror = function() {
document.getElementById('status').innerHTML = "エラー";
if(flag_speech == 0)
vr_function();
};
recognition.onsoundend = function() {
document.getElementById('status').innerHTML = "停止中";
vr_function();
};
recognition.onresult = function(event) {
var results = event.results;
for (var i = event.resultIndex; i < results.length; i++) {
console.log(`${results[i][0].transcript} : ${results[i][0].confidence}`);
if (results[i].isFinal)
{
d(`final: ${results[i][0].transcript}`);
document.getElementById('result_text').innerHTML = results[i][0].transcript;
vr_function();
}
else
{
document.getElementById('result_text').innerHTML = "[途中経過] " + results[i][0].transcript;
flag_speech = 1;
d(`word: ${results[i][0].transcript}`);
}
}
console.log(results);
const res = [].map.call(results, x => x)
.sort((a, b) => a[0].confidence < b[0].confidence);
const alt = res[0];
console.log('-------');
console.log(alt);
console.log(`final: ${alt.isFinal}`);
write.over(alt[0].transcript, alt.isFinal);
}
flag_speech = 0;
document.getElementById('status').innerHTML = "start";
recognition.start();
}
const d = function (text) {
document.getElementById('debug').innerText += text + '\n';
};
const write = {};
write.over = function (text, clear) {
const elem = document.getElementById('write');
elem.innerText = text;
clearTimeout(write.timer);
if (clear) {
elem.innerText += '。';
write.timer = setTimeout(() => elem.innerText = '', 1000);
}
};
window.onload = function () { vr_function() };
</script>
</head>
<body>
<textarea id="result_text" cols="100" rows="10"></textarea>
<br>
<textarea id="status" cols="100" rows="1"></textarea>
<p>字幕</p>
<pre id="write" style="padding: 1em; background-color: bisque"></pre>
<br>
<pre id="debug" style="display: none;"></pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment