Created
November 25, 2019 07:06
-
-
Save sajanthomas01/8b3162152ae06d8178ac3f2400d9086f to your computer and use it in GitHub Desktop.
modified speech.js
This file contains 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
$(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