How to Add Mic Speech Input Icon in a TEXTAREA

I published article earlier in the day about how to add the mic icon in an input box. But adding this mic icon in a TEXTAREA is not allowed. The HTML5 specifications of W3C allow user to enter text in input box element through speech recognition. This facility, at present is supported by the browsers implementing webkit. These browsers include Chrome, Opera and Safari.

If you add x-webkit-speech attribute to an input box; a microphone / mic / mike icon appears in the input box. Clicking on this icon activates voice recognition.

But mic speech input is not allowed in TEXTAREA element. However, with a bit of CSS and JavaScript –you can design a textarea element with speech input. Here is how you can do it:

First of all, add an INPUT box and a TEXTAREA box in your page. Speech enable the input box with x-webkit-speech

<textarea id="mytextarea"></textarea>
<input id="speechinput" x-webkit-speech />
Screenshot: Speech input facility through x-webkit-speech
Screenshot: Speech input facility through x-webkit-speech

Now you need to stylize the input box so as to make the borders disappear, reduce its size and then position it just to the right of textarea (to imitate placement of mic icon in input box). Here is CSS for doing this:

#speechinput {
    width: 25px; // just wide enough to show mic icon
    height: 25px; // just high enough to show mic icon
    cursor:pointer;
    border: none;
    position: absolute;
    margin-left: 5px;
    outline: none;
    background: transparent;
}
#mytextarea {
    height: 300px;
    width: 100px;
}

You got the trick? We will accept speech input in the usual input box, and then, once the speech input is recognized and converted into text, we will transfer text from input to TEXTAREA.

So, in the end, all we need to do is to transfer the text from input to textarea. This can be easily done with JavaScript:

<script>
var mic = document.getElementById('speechinput');
mic.onfocus = mic.blur;
mic.onwebkitspeechchange = function(e) {
document.getElementById('mytextarea').value = speechinput .value;  
};
</script>

Key in this idea is the onwebkitspeechchange event that takes place when there is a change in x-webkit-speech enabled input box (i.e. when you speak and text gets converted into text in the input box). It was PHPied that published this idea originally.

Please feel free to let me know if you have any questions about this topic. I will be happy to try and help you. Thank you for using TechWelkin.

1 thought on “How to Add Mic Speech Input Icon in a TEXTAREA”

Leave a Comment

Your email address will not be published. Required fields are marked *