jlelse
/
Indieroad
Archived
1
Fork 0

Fix speak.js

This commit is contained in:
Jan-Lukas Else 2020-04-11 20:40:56 +02:00
parent ca7114a589
commit d29c669422
1 changed files with 16 additions and 11 deletions

View File

@ -1,13 +1,14 @@
"use strict";
let synth = window.speechSynthesis;
let voice;
if (synth) {
voice = synth.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang))[0];
function getVoice() {
if (window.speechSynthesis) {
return window.speechSynthesis.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang))[0];
}
return false;
}
function initSpeak() {
if (voice) {
if (window.speechSynthesis) {
let speakBtn = document.querySelector('#speakBtn');
speakBtn.style.display = '';
speakBtn.innerHTML = "<a onclick=\"speak()\">Read to me, please.</a>";
@ -17,19 +18,23 @@ function initSpeak() {
function speak() {
console.log("Start speaking")
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"stopSpeak()\">Stop speaking!</a>";
let textContent = document.querySelector('.content').innerText;
let textContent =
((document.querySelector('article .post-title')) ? document.querySelector('article .post-title').innerText + "\n\n" : "")
+ document.querySelector('article .content').innerText;
let utterThis = new SpeechSynthesisUtterance(textContent);
utterThis.voice = voice;
utterThis.voice = getVoice();
utterThis.onerror = stopSpeak;
utterThis.onend = stopSpeak;
synth.speak(utterThis);
window.speechSynthesis.speak(utterThis);
}
function stopSpeak() {
console.log("Stop speaking")
synth.cancel();
window.speechSynthesis.cancel();
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"speak()\">Read to me, please.</a>";
}
initSpeak();
window.onbeforeunload = function () { stopSpeak(); }
window.onbeforeunload = function () {
stopSpeak();
}
initSpeak();