diff --git a/speech.js b/speech.js index 2a4232a..d6f11cb 100644 --- a/speech.js +++ b/speech.js @@ -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 });