JSFiddle - React, Tailwind, and code Playground
HTML
<p class="error">Данный браузер не поддерживает объект speechSynthesis</p>
<p>При нажатии на «воспроизвести», будет произнесён текст</p>
<p><input type="text" id="word" value="Hello world"></p>
<button id="say">Воспроизвести</button>
<!-- Пример сайта know-online.com -->
CSS
body {
font-family: sans-serif;
}
.error {
color: red;
display: none;
}
JavaScript
if (!window.SpeechSynthesisUtterance) {
document.getElementById("error").style.display = "block";
}
// язык, на котором надо воспроизвести текст
var lang = "en-US";
var synth = window.speechSynthesis,
word = document.getElementById("word"),
voice = '',
supportedVoices = [];
document.getElementById("say").onclick = function() {
if (0 === supportedVoices.length) {
var voices = synth.getVoices();
}
// поиск текущего языке в массиве supportedVoices
for (var i = 0; i < voices.length; i++) {
if (lang == voices[i].lang) {
voice = voices[i];
}
}
// произношение текста
var utterThis = new SpeechSynthesisUtterance(word.value);
utterThis.voice = voice;
synth.speak(utterThis);
}