Jan-Lukas Else

Thoughts of an IT expert

How I use the Speech Synthesis API on my blog

Published on in 👨‍💻 Dev
Updated on
Short link: https://b.jlel.se/s/fd
⚠️ This entry is already over one year old. It may no longer be up to date. Opinions may have changed. When I wrote this post, I was only 20 years old!

I just added the feature to my blog that allows you to have any article read to you. For some articles I already add an MP3 file with a natural sounding pronunciation, but now it is also possible to get articles read aloud that don’t have an MP3 file (if the browser and operating system support this).

There is an experimental SpeechSynthesis API in some browsers (Firefox and Chrome support the function). With a simple call it is possible to have text read aloud:

function speak() {
    let voices = synth.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang));
    if (voices.length == 0) return;
    let utterThis = new SpeechSynthesisUtterance(document.querySelector('.content').innerText);
    utterThis.voice = voices[0];
    synth.speak(utterThis);
}

There is also a jQuery plugin that makes this API easier to use.

In the background, the browser in question seems to be using speech synthesis software of the operating system. On my Linux system with espeak-ng, the reading sounds terrible, while on Windows in the new Edge browser it sounds very natural. What surprises me though is that Firefox and Edge(ium) on the same Windows system offer different voices.

Although browsers sometimes implement a lot of unnecessary ballast, I think such a speech synthesis API is a good idea. So you can offer website visitors to have the content read to them without having to record MP3 files first.

Tags: , , ,

Jan-Lukas Else
Interactions & Comments