In Chrome, the voiceschanged
is firing on page load, so I don't need to call the function that has speechSynthesis.getVoices()
initially in order for my empty array to be filled with voices as long as I have an event listener that calls it when voiceschanged
is fired.
// Store voices
let voices = [];
function getVoices() {
voices = speechSynthesis.getVoices();
// Create an option for each voice in array
voices.forEach((voice) => {
const option = document.createElement('option');
option.value = voice.name;
option.innerText = `${voice.name} ${voice.lang}`;
voicesSelect.appendChild(option);
});
}
// Voices changed
speechSynthesis.addEventListener('voiceschanged', getVoices);
// Not needed (in Chrome at least) because voiceschanged event fires on page load, calling getVoices due to event listener (trying to figure out why)
// getVoices();
I'm just trying to understand this behavior - MDN's explanation of when voiceschanged fires doesn't explain it as far as I can tell:
The voiceschanged event of the Web Speech API is fired when the list
of SpeechSynthesisVoice objects that would be returned by the
SpeechSynthesis.getVoices() method has changed (when the voiceschanged
event fires.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…