I'm currently working on a project where if you click a button and say something the computer will respond. I have set up a const called greetings and inside lays some strings I've put. I then put an if statement in my readOutLoud function. In the if statement the computer checks if the user says any of the keywords (right now it can only respond to how are you) and then uses Math. Floor random which I've also inserted in the if statement to pick one of the 3 choices I've put in the greetings const. So right now if you press the talk button and say how are you it will respond with one of the 3 choices I've put in the greetings const. For some reason the second if statement I've put below the 1st one doesn't work why is that so? The only thing different about the second one is that it's using different keywords and getting another const.
const btn = document.querySelector('.talk');
const content = document.querySelector('.content');
const greetings = [
'If you are good im good to đ',
'Im doin alright',
'Im tired đŽ'
];
const weather = [
'Ask the weatherman!',
'okay I guess'
];
const name = [
'My name is techwali',
'techwali!'
];
const hello = [
'Why hello! How are you doing today?',
'Hey there How are you?'
]
const hru = [
'thats great!',
'Im so sorry to hear that',
'Feel better soon!'
]
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.onstart = function() {
console.log('voice is activated speak into the mic');
};
recognition.onresult = function(event) {
const current = event.resultIndex;
const transcript = event.results[current][0].transcript;
content.textContent = transcript;
readOutLoud(transcript);
}
btn.addEventListener('click', () => {
recognition.start();
});
function readOutLoud(message) {
const speech = new SpeechSynthesisUtterance();
speech.text = 'I dont know what you said';
if(message.includes('how are you')) {
const finalText =
greetings[Math.floor(Math.random() * greetings.length)];
speech.text = finalText;
}
if(message.includes('hey', 'hi', 'hello')) {
const finalText =
hello[Math.floor(Math.random() * hello.length)];
speech.text = finalText;
}
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button class="talk">Talk</button>
<h3 class="content"></h3>
</body>
Aucun commentaire:
Enregistrer un commentaire