Skip to content

Instantly share code, notes, and snippets.

@sajanthomas01
Created November 25, 2019 07:06
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 sajanthomas01/8b3162152ae06d8178ac3f2400d9086f to your computer and use it in GitHub Desktop.
Save sajanthomas01/8b3162152ae06d8178ac3f2400d9086f to your computer and use it in GitHub Desktop.
modified speech.js
$(function() {
// initialize select for materialize
$("select").formSelect();
function populateVoiceList() {
let voices = window.speechSynthesis.getVoices();
var voiceList = "";
for (i = 0; i < voices.length; i++) {
console.log(voices[i].name);
voiceList += `<option value="${i}">${voices[i].name} (${voices[i].lang})</option>`;
}
$("#tts_voice").html("");
$("#tts_voice").append(voiceList);
// need to reinitialize select after dynamic changes in materialize :(
$("select").formSelect();
}
// on click of button we read the text from input field
$(document).on("click", "#tts_button", function() {
let text = $("#tts_input")
.val()
.trim();
// just in the below 2 lines of code magic happens
const speak = new SpeechSynthesisUtterance(text);
//add voice
let voiceSelected = $("#tts_voice").val();
speak.voice = window.speechSynthesis.getVoices()[voiceSelected];
speechSynthesis.speak(speak);
$("#tts_input").val("");
});
//second part lets add voices
populateVoiceList();
//why the below if
/*
voiceschanged: Fired when the contents of the SpeechSynthesisVoiceList, that the getVoices method will return, have changed. Examples include: server-side synthesis where the list is determined asynchronously, or when client-side voices are installed/uninstalled.
*/
//inshort the voice list is loaded asynchronously so once it is loaded it fires a onvoicechanged event
if (
typeof speechSynthesis !== "undefined" &&
speechSynthesis.onvoiceschanged !== undefined
) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment