Last active
August 29, 2015 14:14
-
-
Save autonome/65356e878bf35d421ef8 to your computer and use it in GitHub Desktop.
Web Speech API utility
This file contains hidden or 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
function say(phrase) { | |
speechSynthesis.speak(new SpeechSynthesisUtterance(phrase)); | |
} | |
// words: array of strings | |
function addSpeech(words) { | |
var speechrecognitionlist = new SpeechGrammarList(); | |
speechrecognitionlist.addFromString( | |
"#JSGF V1.0; grammar test; public <simple> = " + | |
words.join(' | ') + ' ;', 1); | |
} | |
// handler: function(interimTranscript, completeTranscript) | |
function recordSpeech(handler) { | |
var recognition = new SpeechRecognition(), | |
interim_transcript = '', | |
final_transcript = '', | |
score = '' | |
recognition.onstart = function(event) { | |
console.log('recognition.onstart') | |
} | |
recognition.onresult = function(event) { | |
console.log("recognition.onresult") | |
// Assemble the transcript from the array of results | |
for (var i = event.resultIndex; i < event.results.length; ++i) { | |
if (event.results[i].isFinal) { | |
console.log("recognition.onresult", "isFinal") | |
final_transcript += event.results[i][0].transcript | |
} else { | |
console.log("recognition.onresult", "not isFinal") | |
interim_transcript += event.results[i][0].transcript | |
score = event.results[i][0].confidence | |
} | |
} | |
console.log("recognition.onresult", "interim_transcript", interim_transcript) | |
handler(interim_transcript, final_transcript) | |
} | |
recognition.onend = function() { | |
recognition.stop() | |
console.log('recognition.onend', "final_transcript", final_transcript) | |
} | |
recognition.start() | |
} | |
addSpeech(['hey']) | |
recordSpeech(function(interim, complete) { | |
console.log('recording results', interim, 'COMPLETE', complete) | |
say(complete) | |
}) | |
/* | |
LOG: | |
"recognition.onstart" | |
"recognition.onend" "final_transcript" "" | |
"recognition.onresult" | |
"recognition.onresult" "not isFinal" | |
"recognition.onresult" "interim_transcript" "hey" | |
"recording results" "hey" "COMPLETE" "" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment