DEV Community

wimdenherder
wimdenherder

Posted on • Updated on

Make your browser speak!

This is so cool, you can let your browser talk, just with the latest javascript in the browser. It's called SpeechSynthesis. Open your javascript console (cmd+opt+j in chrome on mac) and try this:

let utterance = new SpeechSynthesisUtterance("Hello");
speechSynthesis.speak(utterance);
Enter fullscreen mode Exit fullscreen mode

On my computer I heard the words "Hello world" with a Dutch accent! So let's change the nationality of the voice.

Let's first load this in our global memory:

const synth = window.speechSynthesis;
Enter fullscreen mode Exit fullscreen mode

Then search for voices:

synth.getVoices();
Enter fullscreen mode Exit fullscreen mode

The browser returns 67 voice objects. Let's map it to the languageCode (key "lang")

let languageCodes = synth.getVoices().map(voice => voice.lang);
Enter fullscreen mode Exit fullscreen mode

Let's only look at the unique codes with

languageCodes = [...new Set(languageCodes)];
Enter fullscreen mode Exit fullscreen mode

41 results! I bet your mothertongue is also among those. Let's find yours (in my case nl-NL, which is Netherlands)

synth.getVoices().find(voice => voice.lang === 'nl-NL')
Enter fullscreen mode Exit fullscreen mode

The find method returns the first hit. In my case a human bot called Xander, not a typical Dutch name. Let's make this voice say something.

// if you didn't yet load the speech synthesis in the constant synth, you may do so here, then uncomment the next line:
// const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance('Hallo'); // Dutch :)
utterance.voice = synth.getVoices().find(voice => voice.lang === 'nl-NL');
synth.speak(utterance);
Enter fullscreen mode Exit fullscreen mode

It would be nice to make a function that has text and language as input and let the voice speak it.

function speak(text, language) {
    const synth = window.speechSynthesis;
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = synth.getVoices().find(voice => voice.lang === language);
    synth.speak(utterance);
}
Enter fullscreen mode Exit fullscreen mode

Now we can simply use that function and wirite:

speak('hi there','en-UK')
Enter fullscreen mode Exit fullscreen mode

If you are lazy you can also only filter on language (the 'en' = english part) and not on country (the 'UK' = United Kingdom part). So now we split it until the -

function speak(text, language) {
    const synth = window.speechSynthesis;
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = synth.getVoices().find(voice => voice.lang.split('-')[0].toLowerCase() === language.split('-')[0].toLowerCase());
    synth.speak(utterance);
}
Enter fullscreen mode Exit fullscreen mode

Enjoy!

Top comments (0)