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);
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;
Then search for voices:
synth.getVoices();
The browser returns 67 voice objects. Let's map it to the languageCode (key "lang")
let languageCodes = synth.getVoices().map(voice => voice.lang);
Let's only look at the unique codes with
languageCodes = [...new Set(languageCodes)];
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')
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);
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);
}
Now we can simply use that function and wirite:
speak('hi there','en-UK')
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);
}
Enjoy!
Top comments (0)