Back to Snippets

Speech to Text Voice Input JS

A voice input box that types what you say. Press the mic, talk, and finished phrases land in the text box while the words still being recognized show in italics underneath. Press the mic again or Esc to stop. The language menu sets the recognition language, and phrases are joined with a space except in Japanese and Chinese, which are written without spaces. You can still type or edit the text by hand at any point.

It uses the SpeechRecognition interface of the Web Speech API, with the webkit prefix as a fallback. continuous keeps it listening between phrases, and interimResults turns on the partial results for the preview. The result handler walks the results from resultIndex and appends only the ones marked isFinal, so partial words never land in the box. The common error codes, from no-speech and audio-capture to not-allowed, each get their own message, and other codes except aborted show a general one.

Speech recognition works in Chrome, Edge and Safari. Firefox does not ship it yet, so the mic button is disabled there with a note. By default, Chrome sends the audio to a server for recognition, so it needs a connection. Serve the page over HTTPS or from localhost, and give an iframe the microphone permission in its allow attribute. Chrome refuses microphone access to a sandboxed frame without allow-same-origin, such as our editor's live preview, so run the code from a local server to try it.

0
#javascript
#css
#ai
#speech recognition
#voice
#web speech api
#microphone
#input