29 lines
915 B
JavaScript
29 lines
915 B
JavaScript
"use strict";
|
|
|
|
let synth = window.speechSynthesis;
|
|
|
|
function initSpeak() {
|
|
if (synth && document.querySelector('.content')) {
|
|
document.querySelector('#speakBtn').style.display = '';
|
|
stopSpeak();
|
|
}
|
|
}
|
|
|
|
function speak() {
|
|
stopSpeak();
|
|
let voices = synth.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang));
|
|
if (voices.length == 0) return;
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"stopSpeak()\">Stop speaking!</a>";
|
|
let utterThis = new SpeechSynthesisUtterance(document.querySelector('.content').textContent);
|
|
utterThis.voice = voices[0];
|
|
utterThis.onerror = stopSpeak;
|
|
utterThis.onend = stopSpeak;
|
|
synth.speak(utterThis);
|
|
}
|
|
|
|
function stopSpeak() {
|
|
synth.cancel();
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"speak()\">Read to me, please.</a>";
|
|
}
|
|
|
|
window.onload = initSpeak(); |