35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
"use strict";
|
|
|
|
let synth = window.speechSynthesis;
|
|
let voice;
|
|
if (synth) {
|
|
voice = synth.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang))[0];
|
|
}
|
|
|
|
function initSpeak() {
|
|
if (voice) {
|
|
let speakBtn = document.querySelector('#speakBtn');
|
|
speakBtn.style.display = '';
|
|
speakBtn.innerHTML = "<a onclick=\"speak()\">Read to me, please.</a>";
|
|
}
|
|
}
|
|
|
|
function speak() {
|
|
console.log("Start speaking")
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"stopSpeak()\">Stop speaking!</a>";
|
|
let textContent = document.querySelector('.content').innerText;
|
|
let utterThis = new SpeechSynthesisUtterance(textContent);
|
|
utterThis.voice = voice;
|
|
utterThis.onerror = stopSpeak;
|
|
utterThis.onend = stopSpeak;
|
|
synth.speak(utterThis);
|
|
}
|
|
|
|
function stopSpeak() {
|
|
console.log("Stop speaking")
|
|
synth.cancel();
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"speak()\">Read to me, please.</a>";
|
|
}
|
|
|
|
initSpeak();
|
|
window.onbeforeunload = function () { stopSpeak(); } |