Loading...
const voices = speechSynthesis.getVoices();
button.addEventListener('click', () => {
utterance.voice = voices[0];
speechSynthesis.speak(utterance);
});let voices = speechSynthesis.getVoices();
speechSynthesis.addEventListener('voiceschanged', () => {
voices = speechSynthesis.getVoices();
});
button.addEventListener('click', () => {
utterance.voice = voices.find((v) => v.lang === 'en-US') ?? null;
speechSynthesis.cancel();
speechSynthesis.speak(utterance);
});getVoices() can be empty at first, so refresh it on voiceschanged; cancel() stops old speech before new text.
voiceschanged event, because it can be empty at first.cancel() is called before speaking new text, so phrases do not pile up.speechSynthesis.getVoices() return an empty array?Some browsers load voices asynchronously. Call getVoices() again in the voiceschanged event.
Call speechSynthesis.cancel() to stop and clear the queue, or pause() and resume() to pause and continue.
It depends on the voice. Voices with localService set to true run on the device; others may need a network connection.