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

64 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-06-14 16:24:05 +08:00
let isRead = true;
let isChoose = true;
let reader = window.speechSynthesis; // 全局定义朗读者,以便朗读和暂停
2022-06-14 19:19:02 +08:00
let cur_position = 0; // 朗读文本的当前位置
let orig_position = 0; // 朗读文本的初始位置
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") {
cur_position = ev.charIndex;
}
}
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();
let msg = makeUtterance(to_speak.substring(orig_position + cur_position), value);
orig_position = orig_position + cur_position;
cur_position = 0;
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();
orig_position = 0;
cur_position = 0;
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;
}