jlelse
/
Indieroad
Archived
1
Fork 0
This repository has been archived on 2020-05-21. You can view files and clone it, but cannot push or open issues or pull requests.
Indieroad/assets/js/speak.js

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(); }