A Pen by Wesley Smits on CodePen.
Created
March 10, 2023 19:00
-
-
Save ryanbekabe/aeb84627c61a6450a92bef681806eacf to your computer and use it in GitHub Desktop.
Web Speech API - Demo
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
<main class="content"> | |
<h1>How to use JavaScript for Text to Speech</h1> | |
<p>You start by defining the content.</p> | |
<p>Then you pass this into the API.</p> | |
</main> | |
<select name="voices" id="voices"> | |
</select> | |
<button id="speak">Play</button> | |
<button id="pause">Pause</button> |
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
(() => { | |
if (!"speechSynthesis" in window) { | |
alert("Sorry, your browser doesn't support text to speech!"); | |
return; | |
} | |
const button = document.getElementById("speak"); | |
const pauseButton = document.getElementById("pause"); | |
const voiceSelect = document.getElementById("voices"); | |
const synth = window.speechSynthesis; | |
const voices = synth.getVoices(); | |
setVoices(); | |
button.addEventListener("click", () => { | |
if (synth.paused === true) { | |
synth.resume(); | |
return; | |
} | |
const main = document.querySelector("main"); | |
textToSpeech(main.innerText); | |
}); | |
pauseButton.addEventListener("click", () => { | |
synth.pause(); | |
}); | |
function textToSpeech(text) { | |
const msg = new SpeechSynthesisUtterance(); | |
msg.text = text; | |
msg.voice = getSelectedVoice(); | |
synth.speak(msg); | |
} | |
function setVoices() { | |
if (voices.length === 0) { | |
alert("Sorry, it seems this browser does not support different voices."); | |
voiceSelect.remove(); | |
} | |
for (let i = 0; i < voices.length; i++) { | |
const option = document.createElement("option"); | |
option.textContent = `${voices[i].name} (${voices[i].lang})`; | |
if (voices[i].default) { | |
option.textContent += " — DEFAULT"; | |
} | |
option.setAttribute("data-lang", voices[i].lang); | |
option.setAttribute("data-name", voices[i].name); | |
voiceSelect.appendChild(option); | |
} | |
} | |
function getSelectedVoice() { | |
const option = voiceSelect.selectedOptions[0]; | |
return voices.find( | |
(voice) => | |
voice.name === option.dataset.name && voice.lang === option.dataset.lang | |
); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment