Speech recognition does not always produce perfect results. Here we'll display potential alternative results in a selection list.
If you're happy with your results from Lesson 3 and got everything working, continue working in that file. If you'd like to start fresh, you can instead use codelab3solution.html to begin this lesson.
The speech recognizer can be configured to generate alternative results (sometimes called n-best results). To get these results, we'll process the onresult event directly. (Up until now, the webspeech.js library has been processing this event, but here we'll override that.)
Add the following within your <script> tags.
// Handler for speech recognition results.
reco.recognition.onresult = function(event) {
var interim_transcript = '';
// Process all new results, both final and interim.
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
appendSelectOptions('final_span', event.results[i]);
} else {
interim_transcript += event.results[i][0].transcript;
}
}
document.getElementById('interim_span').innerHTML = interim_transcript;
};
// Create a new <select> element containing an <option> for each of the
// speech_recognition_result alternatives.
// Then append this <select> element to destination_id.
function appendSelectOptions(destination_id, speech_recognition_result) {
var select = document.createElement('SELECT')
for (var i = 0; i < speech_recognition_result.length; ++i) {
var option = document.createElement('OPTION')
option.text = speech_recognition_result[i].transcript;
option.value = i;
select.options.add(option)
}
document.getElementById(destination_id).appendChild(select);
}
Test it. Refresh the page and click the microphone. You'll see the final results show up in selection drop downs. However, each selection only has one option, so far...
Add the following line just below the "reco.continuous" line.
reco.maxAlternatives = 10;
Test it. Refresh the page and click the microphone. Now the selection drop downs will contain up to 10 alternative results.
These alternative results are listed in order from greatest confidence to least, corresponding to the order the speech recognizer provided them.
When CreateEmail is called, it should be passed a string that corresponds to the selections that the user made. Implementing this is left as an exercise for the reader.
You've learned the techniques to add speech to your website. You've seen how the webspeech.js library makes it easy to add speech with just a few lines of code, and how you can customize it further as needed.
Add speech to your website. Use whatever parts of webspeech.js you need, and overwrite anything you need to change. Or just use webspeech.js as code snippets for your app. Or if you want complete control, skip the library and code directly to the Web Speech API as in this Tutorial
Happy coding!
This Codelab by Glen Shires. Visit me on Google+!