Skip to content

Instantly share code, notes, and snippets.

@richjenks
Last active November 18, 2015 18:16
Show Gist options
  • Save richjenks/76da20af9a709436768d to your computer and use it in GitHub Desktop.
Save richjenks/76da20af9a709436768d to your computer and use it in GitHub Desktop.
Demo of the Speech Synthesis API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Speech Synthesis Test</title>
<style>
* { box-sizing: border-box; }
body { font-family: sans-serif; }
#left, #right { width: 50%; padding: 1em; }
#left { float: left; }
#right { float: right; }
a:link, a:visited { color: blue; }
a:target { color: red !important; }
</style>
</head>
<body>
<h1>Speech Synthesis Test</h1>
<div id="left"><ul id="voiceList"></ul></div>
<div id="right">
<textarea id="text" rows="5" cols="50">Hello, World!</textarea>
<br>
<button id="speak">Speak</button>
<button id="slower">Slower</button>
<button id="faster">Faster</button>
<button id="lower">Lower</button>
<button id="higher">Higher</button>
<button id="louder">Louder</button>
<button id="quieter">Quieter</button>
</div>
<script>
var utterance = new SpeechSynthesisUtterance(),
speak = document.getElementById("speak"),
slower = document.getElementById("slower"),
faster = document.getElementById("faster"),
lower = document.getElementById("lower"),
higher = document.getElementById("higher"),
quieter = document.getElementById("quieter"),
louder = document.getElementById("louder"),
text = document.getElementById("text");
// Delay links and events because speechSynthesis is funny
speechSynthesis.getVoices();
setTimeout(function () {
// Output voice list
var voiceList = document.getElementById("voiceList");
speechSynthesis.getVoices().forEach(function(voice, index) {
voiceList.innerHTML += '<li><a href="#" class="voice" data-voice="' + index + '">' + voice.name + '</a></li>';
});
// Add event listeners
var voiceLinks = document.querySelectorAll(".voice");
for (var i = 0; i < voiceLinks.length; i++) {
voiceLinks[i].addEventListener("click", function (event) {
utterance.voice = speechSynthesis.getVoices()[this.dataset.voice];
});
}
}, 100);
// Say text when button is clicked
speak.addEventListener("click", function (event) {
utterance.text = text.value;
speechSynthesis.speak(utterance);
});
slower.addEventListener("click", function (event) { utterance.rate -= 0.1; });
faster.addEventListener("click", function (event) { utterance.rate += 0.1; });
lower.addEventListener("click", function (event) { utterance.pitch -= 0.1; });
higher.addEventListener("click", function (event) { utterance.pitch += 0.1; });
quieter.addEventListener("click", function (event) { utterance.volume -= 0.1; });
louder.addEventListener("click", function (event) { utterance.volume += 0.1; });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment