Mobile websites opened one whole new world for bloggers. Nowadays many websites are mostly visited by mobile devices like smartphones or tablets. Users like to use speech recognition feature instead of typing the query they want to search the website. As all we know Google had implemented this long ago on its home page.

google-now-speak

This article will help you to add speech recognition to any input box in your website. It could be a text box to text area in the form of your website. We basically will use HTML5 Web Speech API to perform this task. It is easy trick to add speech recognition to any input box in your website.

We assume you have a search form in your website already. For example, let us take the code below as our search form. Don’t forget to change website name in action field of form.

<form id=”searchBox” method=”get” action=”http://techmuzz.com”>
<div class=”speech”>
<input type=”text” name=”s” id=”transcript” placeholder=”Speak” />
<img onclick=”startDictation()” src=”https://i.imgur.com/cHidSVu.gif” />
</div>
</form>

You can use your own CSS but if you want to try it right now then just copy paste the code below and replace CSS selectors in the code below.

<style>
.speech {border: 1px solid #DDD; width: 300px; padding: 0; margin: 0}
.speech input {border: 0; width: 240px; display: inline-block; height: 30px;}
.speech img {float: right; width: 40px }
</style>

Lastly the core mechanism that will help you to add speech recognition to any input box is given below. You can make changes in the code below like language you think is more suitable for your visitors.

<script>
function startDictation() {
if (window.hasOwnProperty(‘webkitSpeechRecognition’)) {
var recognition = new webkitSpeechRecognition();

recognition.continuous = false;
recognition.interimResults = false;

recognition.lang = “en-US”;
recognition.start();

recognition.onresult = function(e) {
document.getElementById(‘transcript’).value
= e.results[0][0].transcript;
recognition.stop();
document.getElementById(‘searchBox’).submit();
};

recognition.onerror = function(e) {
recognition.stop();
}

}
}
</script>

If you want to test how Dictation works through this API then you can visit Dictation App. The app uses the same API and gives choice to select languages as drop down menu. They use text area to write transcribed text instead of the text box.

When a user clicks on the mic button in the search box then the JavaScript check if the user’s browser supports speech recognition or not. If so, it waits for the text to arrive from your website’s search page and then submit the form.

If you add this API to a page that is not httpsS website then for every time you click the mic image it will ask your permission else on httpsS website it saves the result for the website for future use.

That’s all. If you have any doubt related this article then feel free to ask in the comment section. We will be glad to help you.

Enjoy & Stay Techie…