#javascript #webkitspeechrecognition
#javascript #распознавание webkitspeechrecognition
Вопрос:
У меня есть анкета из 6 вопросов. Они представлены с помощью SpeechSynthesis. После каждого вопроса мне нужно дождаться устного ответа, который я обработаю, прежде чем задавать следующий вопрос. Мой код является попыткой этого. Код действительно проходит обратный вызов. Но, как последовательно обработать логику, ‘сформулировать вопрос’, ‘прослушать’, ‘сформулировать следующий вопрос’, ‘прослушать’…
//..ToDo: Because we need verbal response for each question,
//.. we need to change the recognition.onResult call back
function processPromptedInteraction(event)
{
var speechToText = event.results[0][0].transcript;
if (speechToText.includes('yes'))
{ }
else if (speechToText.includes('no'))
{ }
else
{ }
}
var strQuestion = '';
for (i = 0; i < questions[i].length; i )
{
recognition.onresult = processPromptedInteraction; //.. Callback function
strQuestion = questions[i].question;
say(strQuestion);
}
Комментарии:
1. Примечание: Распознавание речи и SpeechSynthesis работают. Это логика, с которой я борюсь
Ответ №1:
events
являются асинхронными, поэтому ваш код не ждет, пока пользователи ответят на вопросы один за другим. Надеюсь, что следующее решение сработает для вас. Дайте мне знать, если я чего-то не понимаю.
Примечание: Код может здесь не запускаться из-за безопасности браузера. Используйте ссылку jsfiddle ниже, чтобы запустить код. Окончательный результат смотрите в консоли браузера
https://jsfiddle.net/ajai/L8p4aqtr/
class Questions {
constructor(questions) {
this.questions = questions;
this.currentIndex = 0;
this.MAX = this.questions.length - 1;
// answers hash
this.answers = questions.reduce((hash, q) => {
hash[q] = '';
return hash;
}, {});
this.initSpeech();
}
initSpeech() {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
this.speechSynthesis = window.speechSynthesis;
this.recognition = new webkitSpeechRecognition();
this.recognition.continuous = true;
this.recognition.interimResults = false;
this.recognition.onresult = this.recognize.bind(this);
}
recognize(event) {
const last = event.results.length - 1;
const result = event.results[last][0].transcript;
if (result.includes('yes')) {
this.setAnswer('Yes');
this.next();
} else if (result.includes('no')) {
this.setAnswer('No');
this.next();
} else {
// ask same question again
this.say('Can't recognize your answer');
this.ask();
}
}
setAnswer(answer) {
this.answers[this.questions[this.currentIndex]] = answer;
}
start() {
this.currentIndex = 0;
this.recognition.start();
this.ask();
return this;
}
stop() {
this.recognition.stop();
this.onComplete amp;amp; this.onComplete(this.answers);
}
ask() {
const questionToAsk = this.questions[this.currentIndex];
this.say(questionToAsk);
}
say(msg) {
const synth = new SpeechSynthesisUtterance(msg);
this.speechSynthesis.speak(synth);
}
next() {
if (this.currentIndex < this.MAX) {
this.currentIndex ;
this.ask();
} else {
this.stop();
}
}
getAnswers() {
return this.answers;
}
static create(questions) {
return new Questions(questions);
}
}
// const q = new Questions(['Question 1?', 'Question 2?', 'Question 3?']);
const q = Questions.create(['Question 1?', 'Question 2?', 'Question 3?']);
q.start().onComplete = function(result) {
console.log(this.answers);
};
Комментарии:
1. Очень интересное решение. Пока я не могу использовать это, поскольку у меня уже есть другой класс с объектом SpeechRecognition, я посмотрю, как я могу включить некоторые ваши элементы. Скоро обновлю этот пост. Приветствия
2. Спасибо тебе, Аджай. Я перепроектирую свой код, чтобы приспособить его к вашей модели. Прототип сработал. Теперь для интеграции в мою систему, в которой уже есть огромный компонент speechrecog. Приветствия.