JavaScript30 - Day 20

By Camilla Krag Jensen naxoc |

Day 20 of #javascript30 is about speech recognition in the browser. It is safe to say I had a ton of fun and that I got completely carried away.

SpeechRecognition

The browser's interface for speech recognition is pretty easy to work with. I'm amazed at how good it is at guessing what you say. Granted - it will completely mishear from time to time, but so do I sometimes!

Speech recognition language

As always when working with web stuff, my initial reaction to the speech recognition was: oh, that's cool, I bet it only works in English and in the US just like recipes, address forms and all that. But more and more - I am proven wrong on the web. It made me happy that I can set the language to Danish even though only about 5 million people speak it. Here is how you set the language:

const recognition = new SpeechRecognition();
// Set the language.
recognition.lang = 'da-DK ';

Simply set the lang property to a new language code. The language code is an ISO language code. A list of language codes can be found here.

Listening for results

You listen for speech input with the result event. The event variable will have a ton of info, but you can pull the string out like this by making the result an array and running map on it a couple of times:

recognition.addEventListener('result', e => {
    const transcript = Array.from(e.results)
        .map(result => result[0])
        .map(result => result.transcript)
        .join('');
    // Update stuff with the transcript string.
    if (e.results[0].isFinal) {
            // The user paused.
    }
});

Putting it all together.

For now speech recognition only works in Chrome. I made a page that can use voice commands to change background color. Go check it out! Make sure you use Chrome for this. It doesn't work in Firefox.

It supports Danish, Spanish, and English. It was so much fun to play around with. I really feel like my taking the time to do #javascript30 is starting to come back. I feel so much more confident and I write nicer code much faster now.