JSFiddle - React, Tailwind, and code Playground
Using HTML5 Speech Recognition and Text to Speech. (1) Ask a question and check answer.
by abubelinha
HTML
<html>
<head>
<title>Math Quiz</title>
<link href="mathquiz.css" rel="stylesheet" />
</head>
<body>
<h3>
Using HTML5 Speech Recognition and Text to Speech
<br>(taken from <a href="http://stephenwalther.com/archive/2015/01/05/using-html5-speech-recognition-and-text-to-speech" target=_blank>here</a>)
<br>(1). As a question and check answer.
</body>
</html>
CSS
body {background:white;}
JavaScript
speak('This is an enquiry!');
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
// ask a question and get an answer
function ask(text, callback) {
// ask question
speak(text, function () {
// get answer
var recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.onend = function (e) {
if (callback) {
callback('no results');
}
};
recognition.onresult = function (e) {
// cancel onend handler
recognition.onend = null;
if (callback) {
callback(null, {
transcript: e.results[0][0].transcript,
confidence: e.results[0][0].confidence
});
}
}
// start listening
recognition.start();
});
}
ask('What is your favorite color?', function (err, result) {
if (result && result.transcript == 'blue') {
speak('Right!');
} else {
speak('Wrong!');
}
});