fix: 移动端朗读改为同步手势触发并兼容cancel后延迟播放

This commit is contained in:
guoqingshan
2026-08-02 12:24:05 +08:00
parent ab427d2fdc
commit 5dec7fb30c
+18 -16
View File
@@ -1,5 +1,6 @@
var speechVoices = [];
var speechVoicesLoaded = false;
var speechTimer = null;
function refreshSpeechVoices() {
if (!window.speechSynthesis) return;
@@ -36,28 +37,20 @@ function buildSpeechUtterance(text, lang) {
}
function doSpeak(text, lang) {
if (!window.speechSynthesis || !text) return;
if (!window.speechSynthesis || !window.SpeechSynthesisUtterance || !text) return;
window.speechSynthesis.cancel();
window.speechSynthesis.speak(buildSpeechUtterance(text, lang));
if (speechTimer) clearTimeout(speechTimer);
var utterance = buildSpeechUtterance(text, lang);
speechTimer = setTimeout(function() {
window.speechSynthesis.speak(utterance);
if (window.speechSynthesis.paused) window.speechSynthesis.resume();
}, 60);
}
function speakText(text, lang) {
if (!text || !window.speechSynthesis) return;
refreshSpeechVoices();
if (speechVoicesLoaded) {
doSpeak(text, lang);
return;
}
var attempts = 0;
var timer = setInterval(function() {
attempts++;
refreshSpeechVoices();
if (speechVoicesLoaded || attempts >= 8) {
clearInterval(timer);
doSpeak(text, lang);
}
}, 80);
doSpeak(text, lang);
window.speechSynthesis.getVoices();
}
@@ -71,3 +64,12 @@ function initSpeech() {
if (document.readyState === 'complete') initSpeech();
else document.addEventListener('DOMContentLoaded', initSpeech);
function warmSpeechVoices() {
if (!window.speechSynthesis) return;
window.speechSynthesis.getVoices();
refreshSpeechVoices();
}
document.addEventListener('touchstart', warmSpeechVoices, { once: true, passive: true });
document.addEventListener('pointerdown', warmSpeechVoices, { once: true, passive: true });