I am currently learning Speech Recognition(JavaScript).
I want to make a assistant with JavaScript. My problem is that everything I say I can not use. And I want that to start the function ai() when I say Hello.
My Code:
function tsCheck(){
if (window.transcript == "Hi"){
ai();
}
}
function speak(a){
var msg = new SpeechSynthesisUtterance(a);
window.speechSynthesis.speak(msg);
}
function ai(){
speak('How are you?');
if (window.transcript == "good"){
speak("cool");
}
}
var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.onresult = function(event) {
var current = event.resultIndex;
window.transcript = event.results[current][0].transcript;
console.log(window.transcript);
}
recognition.start();
You forgot to call the tsCheck()
function in your recognition.onresult
callback.
recognition.onresult = function(event) {
var current = event.resultIndex;
window.transcript = event.results[current][0].transcript;
tsCheck(); //ADD THIS
console.log(window.transcript);
}
EDIT: in the tsCheck
method, you need to compare the result to a lowercase string (notice "hi" instead of "Hi".
function tsCheck(){
if (window.transcript == "hi"){
ai();
}
}
EDIT 2: To keep responding to inputs, I added a parameter to the ai()
function. This isn't of any real practical use, however, because it doesn't keep track of the context of the conversation.
function ai(string){
speak(string);
}
function tsCheck(){
if (/hi/i.test(window.transcript)){
ai("How are you");
}
if (/good/i.test(window.transcript)){
ai("Cool");
}
}
Also using a regex to test the strings, as it sometimes has spaces before and after the word.