'How to call recognition.onresult to an API function in Javascript?
Im working on a voice recognition system where a voice command can pull up NASA's Astronomy Picture of the Day through their NASA API. I've made some simple code just to test it out by saying "Check Steve" and it'll check the check box named Steve. However when I say "Astronomy Picture of the Day", it returns "undefined" rather than the picture or text from the NASA API. Why is that?
var message = document.querySelector('#message');
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var grammar = '#JSGF V1.0;'
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.onspeechend = function() {
recognition.stop();
};
recognition.onerror = function(event) {
message.textContent = 'Error occurred in recognition: ' + event.error;
}
document.querySelector('#btnGiveCommand').addEventListener('click', function(){
recognition.start();
sendApiRequest()
});
async function sendApiRequest(){
let API_KEY = "7RTzkUMJOC8QYxM4COFoVha8NvAhxcZH2Ca7Px0G"
let response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`);
console.log(response)
let event = await response.json()
console.log(event)
// how do i call the line of code right below this comment to this function?
}
recognition.onresult = function(event) {
var last = event.results.length - 1;
var command = event.results[last][0].transcript;
message.textContent = 'Voice Input: ' + command + '.';
if(command.toLowerCase() === 'astronomy picture of the day'){
document.querySelector("#chkSteve").innerHTML = event.explanation
}
else if (command.toLowerCase() === 'select tony'){
document.querySelector('#chkTony').checked = true;
}
else if (command.toLowerCase() === 'select bruce'){
document.querySelector('#chkBruce').checked = true;
}
else if (command.toLowerCase() === 'select nick'){
document.querySelector('#chkNick').checked = true;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|