EnglishPal/app/static/js/read.js

49 lines
1.2 KiB
JavaScript
Raw Normal View History

var Reader = (function() {
let reader = window.speechSynthesis;
let current_position = 0;
let original_position = 0;
let to_speak = "";
2024-06-22 09:04:25 +08:00
let current_rate = 1; // 添加这一行,设置默认速率为 1
function makeUtterance(str, rate) {
let msg = new SpeechSynthesisUtterance(str);
msg.rate = rate;
msg.lang = "en-US";
msg.onboundary = ev => {
if (ev.name === "word") {
current_position = ev.charIndex;
}
}
return msg;
}
function read(s, rate) {
to_speak = s.toString();
original_position = 0;
current_position = 0;
let msg = makeUtterance(to_speak, rate);
reader.speak(msg);
}
2024-06-22 09:04:25 +08:00
function updateRate(rate) {
// 停止当前的朗读
stopRead();
// 更新当前速率
current_rate = rate;
// 重新开始朗读
read(to_speak, current_rate);
}
function stopRead() {
reader.cancel();
}
return {
read: read,
2024-06-22 09:04:25 +08:00
stopRead: stopRead,
updateRate: updateRate // 添加这一行,将 updateRate 方法暴露出去
};
}) ();