Skip to content

Instantly share code, notes, and snippets.

@jaikt
Created November 24, 2021 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaikt/0950c482dc3e9652e5d9003a8c735840 to your computer and use it in GitHub Desktop.
Save jaikt/0950c482dc3e9652e5d9003a8c735840 to your computer and use it in GitHub Desktop.
Text To Speech Converter - @file-3
const textarea = document.querySelector("textarea"),
voiceList = document.querySelector("select"), // Selection
speechBtn = document.querySelector("button");
let synth = speechSynthesis,
isSpeaking = true;
voices();
function voices(){
for(let voice of synth.getVoices()){
let selected = voice.name === "Google US English" ? "selected" : "";
let option = `<option value="${voice.name}" ${selected}>${voice.name} (${voice.lang})</option>`;
voiceList.insertAdjacentHTML("beforeend", option); // Getting Verbal's
}
}
synth.addEventListener("voiceschanged", voices);
function textToSpeech(text){
let utterance = new SpeechSynthesisUtterance(text);
for(let voice of synth.getVoices()){
if(voice.name === voiceList.value){
utterance.voice = voice;
}
}
synth.speak(utterance);
}
speechBtn.addEventListener("click", e =>{
e.preventDefault();
if(textarea.value !== ""){
if(!synth.speaking){
textToSpeech(textarea.value);
}
if(textarea.value.length > 80){
setInterval(()=>{
if(!synth.speaking && !isSpeaking){
isSpeaking = true;
speechBtn.innerText = "Convert To Speech"; //Execute
}else{
}
}, 500);
if(isSpeaking){
synth.resume();
isSpeaking = false;
speechBtn.innerText = "Pause Speech"; //Pause
}else{
synth.pause();
isSpeaking = true;
speechBtn.innerText = "Resume Speech"; //Resume
}
}else{
speechBtn.innerText = "Convert To Speech"; //Execute
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment