Last active
October 17, 2020 18:41
-
-
Save sharkdeng/307fde3e9a54d129ca22c17a301947a4 to your computer and use it in GitHub Desktop.
SpeechSynthesisUtterance-working-1
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
<html> | |
<head> | |
</head> | |
<body> | |
<form> | |
<input type='text'></input> | |
<select id='voiceSelect'></select> | |
<input type="submit"></input> | |
</form> | |
<script> | |
function speechTool() { | |
var synth = speechSynthesis; | |
var voices = synth.getVoices(); | |
// populate voices | |
var inputForm = document.querySelector('form'); | |
var inputTxt = document.querySelector('input'); | |
for(var i = 0; i < voices.length; i++) { | |
var option = document.createElement('option'); | |
option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; | |
option.value = i; | |
if(voices[i].default) { | |
option.textContent += ' -- DEFAULT'; | |
} | |
option.setAttribute('data-lang', voices[i].lang); | |
option.setAttribute('data-name', voices[i].name); | |
document.querySelector('select').appendChild(option); | |
} | |
// sound the input text | |
inputForm.onsubmit = function(event) { | |
event.preventDefault(); | |
var utterThis = new SpeechSynthesisUtterance(inputTxt.value); | |
utterThis.voice = voices[voiceSelect.value]; | |
synth.speak(utterThis); | |
inputTxt.blur(); | |
} | |
} | |
speechTool(); | |
// required for Chrome | |
if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) { | |
speechSynthesis.onvoiceschanged = speechTool; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment