let synth = window.speechSynthesis;
speakBtn.addEventListener("click", speak);
stopBtn.addEventListener("click", stop);
phrase.addEventListener("keydown", handleEnter);
preferGoogle.addEventListener("change", updateVoices);
synth.addEventListener("voiceschanged", updateVoices);
// Say `phrase` with the selected `availableVoices`.
function speak() {
const utterance = new SpeechSynthesisUtterance(phrase.value);
utterance.voice = findVoice(availableVoices.value);
synth.speak(utterance);
}
// Find a voice by its voiceURI.
function findVoice(URI) {
let voice = synth.getVoices().find(
(v) => v.voiceURI === URI
);
return voice;
}
// Stop speaking.
function stop() {
synth.cancel();
}
// Get all voices and update the select
function updateVoices() {
let voices = synth.getVoices()
// "Google" voices are only available in Chrome.
.filter((v) => !preferGoogle.checked || v.name.includes("Goog"))
// Group available voices by their lang.
let grouped = Map.groupBy(voices, (v) => v.lang);
renderVoiceSelect(grouped);
}
function handleEnter(event) {
if (event.key === "Enter") {
event.preventDefault();
speak();
}
}
// Add the available voices to the dropdown.
function renderVoiceSelect(voices) {
availableVoices.replaceChildren(defaultVoice);
let sortedKeys = [...voices.keys()].toSorted();
sortedKeys.forEach((k) => {
let optgroup = document.createElement('optgroup');
optgroup.label = k;
voices.get(k).forEach((voice) => {
let option = document.createElement('option');
option.innerText = voice.name;
option.value = voice.voiceURI;
optgroup.append(option);
});
availableVoices.append(optgroup);
});
}
// Load the available voices.
updateVoices();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.