On Google.com you'll find a little microphone icon embedded inside the search box. When you click the icon, say something and your voice is quickly transcribed into words. Sounds like magic, right? Well, you can also include similar speech recognition capabilities to your own website with a few lines of code. So your visitors can search your website, or even fill forms, using just their voice.
Add Voice Recognition to your Website
The HTML5 Web Speech API has been around for a few years now but it takes slightly more work now to include it in your website. Earlier, you could add the attribute x-webkit-speech
to any form input field and it would become voice capable. The x-webkit-speech
attribute has however been deprecated and you are now required to use the JavaScript API to include speech recognition. Here's the updated code:
<!-- CSS Styles --> <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> <!-- Search Form --> <form id="lj" method="get" action="https://www.google.com/search"> <div class="speech"> <input type="text" name="q" id="transcript" placeholder="Speak" /> <img onclick="startDictation()" src="//i.imgur.com/cHidSVu.gif" /> </div> </form> <!-- HTML5 Speech Recognition API --> <script> function startDictation() { if (window.hasOwnProperty('webkitSpeechRecognition')) { var recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimResults = false; recognition.lang = "en-US"; recognition.start(); recognition.onstart = function() { document.getElementById('transcript').value= 'Say Something..'; } recognition.onresult = function(e) { document.getElementById('transcript').value= e.results[0][0].transcript; recognition.stop(); document.getElementById('lj').submit(); }; recognition.onerror = function(e) { alert('Somthing went wrong. Please try again.') document.getElementById('transcript').value= ''; recognition.stop(); } } } </script>
We have the CSS to place the microphone image inside the input box, the form code containing the input button, and the JavaScript that does all the heavy work. When the user clicks the microphone icon, the JavaScript checks if the user's browser supports speech recognition and it waits for the transcribed text to arrive from Google servers and then submits the form.
Some notes:
- Only Google Chrome desktop browser supports the speech recognition API.
- If the HTML form/search box is embedded inside an HTTPS website, the browser will not repeatedly ask for permission to use the microphone.
- You can change the value of the recognition.lang property from ‘en-US' to another language. See the complete list of supported languages.
- For more details please visit Google Voice Driven Web Apps.