Created
January 16, 2022 19:17
-
-
Save cgewecke/6313a2edf8cb2358ff4592eb55ea3392 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
</head> | |
<body> | |
<div> | |
<div> | |
<span lang="fr-FR"> A Scottsdale le nom de la cité et pronouncé </span> | |
<span lang="en-US"> Scottsdale </span> | |
</div> | |
<div> | |
<span lang="en-US">In Paris the name of the city is pronounced</span> | |
<span lang="fr-FR">Paris</span> | |
</div> | |
<div> | |
<button id="speak"> Click me </button> | |
</div> | |
<script> | |
// All this code is in an event callback that guarantees the page is loaded and usable | |
window.addEventListener('DOMContentLoaded', () => { | |
// This is the button you click to execute the tts logic | |
const button = document.getElementById("speak"); | |
// Chrome loads its voices from the cloud so we needs to wait until they're available. | |
speechSynthesis.addEventListener("voiceschanged", () => { | |
// Get voices | |
const voices = speechSynthesis.getVoices() | |
// Get references to all the span elements | |
const spans = document.getElementsByTagName('span'); | |
// AFAIK browsers won't turn sound on unless the user interacts with the page somehow | |
// So we need to wait for a button click... | |
button.addEventListener("click", () => { | |
// Cycle through the spans, getting the text and their language attribute | |
for (const span of spans) { | |
const lang = span.getAttribute("lang"); | |
const text = span.innerText.trim(); | |
// Search the voices array for the language of current span | |
const voice = voices.find(v => v.lang === lang); | |
// Get an utterance instance, set its voice to the one specified by the tag, and speak. | |
const utterance = new SpeechSynthesisUtterance(text); | |
utterance.voice = voice; | |
speechSynthesis.speak(utterance); | |
// The methods below are useful for debugging in the chrome developer tools console | |
// `.dir` logs a clickable object which lets you see all the fields | |
// `.log` is good for text | |
// console.log('text --> ' + text); | |
// console.dir(voice); | |
} | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment