我目前正在做一个项目,如果你点击一个按钮并说出一些东西,计算机会做出响应。我已经设置了一个名为 greetings 的常量,里面放了一些我已经放好的字符串。然后我在 readOutLoud 函数中放置了一个 if 语句。在 if 语句中,计算机检查用户是否说了任何关键字(现在它只能响应你的情况),然后使用 Math。我还在 if 语句中插入了 Floor random 以选择我在问候 const 中放入的 3 个选项之一。所以现在,如果你按下通话按钮并说你好吗,它会回复我在问候语中加入的 3 个选项之一。出于某种原因,我放在第一个 if 语句下面的第二个 if 语句不起作用,为什么会这样?第二个唯一不同的是它'
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);
}
相关分类