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

40 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-04-11 17:27:10 +00:00
"use strict";
2020-04-11 18:40:56 +00:00
function getVoice() {
if (window.speechSynthesis) {
return window.speechSynthesis.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang))[0];
}
return false;
2020-04-11 17:27:10 +00:00
}
function initSpeak() {
2020-04-11 18:40:56 +00:00
if (window.speechSynthesis) {
2020-04-11 17:27:10 +00:00
let speakBtn = document.querySelector('#speakBtn');
speakBtn.style.display = '';
speakBtn.innerHTML = "<a onclick=\"speak()\">" + speakText + "</a>";
2020-04-11 17:27:10 +00:00
}
}
function speak() {
console.log("Start speaking")
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"stopSpeak()\">" + stopSpeakText + "</a>";
2020-04-11 18:40:56 +00:00
let textContent =
((document.querySelector('article .post-title')) ? document.querySelector('article .post-title').innerText + "\n\n" : "")
+ document.querySelector('article .content').innerText;
2020-04-11 17:27:10 +00:00
let utterThis = new SpeechSynthesisUtterance(textContent);
2020-04-11 18:40:56 +00:00
utterThis.voice = getVoice();
2020-04-11 17:27:10 +00:00
utterThis.onerror = stopSpeak;
utterThis.onend = stopSpeak;
2020-04-11 18:40:56 +00:00
window.speechSynthesis.speak(utterThis);
2020-04-11 17:27:10 +00:00
}
function stopSpeak() {
console.log("Stop speaking")
2020-04-11 18:40:56 +00:00
window.speechSynthesis.cancel();
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"speak()\">" + speakText + "</a>";
2020-04-11 17:27:10 +00:00
}
2020-04-11 18:40:56 +00:00
window.onbeforeunload = function () {
stopSpeak();
}
initSpeak();