40 lines
1.3 KiB
JavaScript
40 lines
1.3 KiB
JavaScript
"use strict";
|
|
|
|
function getVoice() {
|
|
if (window.speechSynthesis) {
|
|
return window.speechSynthesis.getVoices().filter(voice => voice.lang.startsWith(document.querySelector('html').lang))[0];
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function initSpeak() {
|
|
if (window.speechSynthesis) {
|
|
let speakBtn = document.querySelector('#speakBtn');
|
|
speakBtn.style.display = '';
|
|
speakBtn.innerHTML = "<a onclick=\"speak()\">" + speakText + "</a>";
|
|
}
|
|
}
|
|
|
|
function speak() {
|
|
console.log("Start speaking")
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"stopSpeak()\">" + stopSpeakText + "</a>";
|
|
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 = getVoice();
|
|
utterThis.onerror = stopSpeak;
|
|
utterThis.onend = stopSpeak;
|
|
window.speechSynthesis.speak(utterThis);
|
|
}
|
|
|
|
function stopSpeak() {
|
|
console.log("Stop speaking")
|
|
window.speechSynthesis.cancel();
|
|
document.querySelector('#speakBtn').innerHTML = "<a onclick=\"speak()\">" + speakText + "</a>";
|
|
}
|
|
|
|
window.onbeforeunload = function () {
|
|
stopSpeak();
|
|
}
|
|
initSpeak(); |