1
0
Fork 0
EnglishPal/app/static/js/fillword.js

65 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2022-06-14 16:24:05 +08:00
let isRead = true;
let isChoose = true;
let reader = window.speechSynthesis; // 全局定义朗读者,以便朗读和暂停
2022-07-18 15:57:23 +08:00
let current_position = 0; // 朗读文本的当前位置
let original_position = 0; // 朗读文本的初始位置
2022-06-14 19:19:02 +08:00
let to_speak = ""; // 朗读的初始内容
2022-06-14 16:24:05 +08:00
function getWord() {
return window.getSelection ? window.getSelection() : document.selection.createRange().text;
}
2022-06-14 16:24:05 +08:00
function fillInWord() {
let word = getWord();
if (isRead) read(word);
if (!isChoose) return;
const element = document.getElementById("selected-words");
element.value = element.value + " " + word;
}
2022-06-14 16:24:05 +08:00
document.getElementById("text-content").addEventListener("click", fillInWord, false);
2022-06-14 19:19:02 +08:00
function makeUtterance(str, rate) {
let msg = new SpeechSynthesisUtterance(str);
msg.rate = rate;
msg.lang = "en-US"; // TODO: add language options menu
msg.onboundary = ev => {
if (ev.name == "word") {
2022-07-18 15:57:23 +08:00
current_position = ev.charIndex;
2022-06-14 19:19:02 +08:00
}
}
return msg;
}
const sliderValue = document.getElementById("rangeValue"); // 显示值
const inputSlider = document.getElementById("rangeComponent"); // 滑块元素
inputSlider.oninput = () => {
let value = inputSlider.value; // 获取滑块的值
sliderValue.textContent = value + '×';
if (!reader.speaking) return;
reader.cancel();
2022-07-18 15:57:23 +08:00
let msg = makeUtterance(to_speak.substring(original_position + current_position), value);
original_position = original_position + current_position;
current_position = 0;
2022-06-14 19:19:02 +08:00
reader.speak(msg);
};
2022-06-14 16:24:05 +08:00
function read(s) {
2022-06-14 19:19:02 +08:00
to_speak = s.toString();
2022-07-18 15:57:23 +08:00
original_position = 0;
current_position = 0;
2022-06-14 19:19:02 +08:00
let msg = makeUtterance(to_speak, inputSlider.value);
2022-06-14 16:24:05 +08:00
reader.speak(msg);
}
2022-06-14 16:24:05 +08:00
function onReadClick() {
isRead = !isRead;
2022-06-14 16:24:05 +08:00
if (!isRead) {
reader.cancel();
}
}
2022-06-14 16:24:05 +08:00
function onChooseClick() {
isChoose = !isChoose;
2022-07-18 15:57:23 +08:00
}