on
Italy
- Get link
- X
- Other Apps
var utterance = new SpeechSynthesisUtterance();What we’re doing here is creating a new instance of a synthesized utterance. Think of this as a little envelope that contains instructions telling the browser what it should say and how to say it.
utterance.text = 'My name\'s Guybrush Threepwood, and I want to be a pirate!';
speechSynthesis.speak(utterance);Wow, a talking computer. As easy as that.
speechSynthesis.getVoices().forEach(function(voice) { console.log('Hi! My name is ', voice.name); });
// Tell Chrome to wake up and get the voices. speechSynthesis.getVoices(); setTimeout(function () { // After 1 second, get the voices now Chrome is listening. speechSynthesis.getVoices().forEach(function (voice) { console.log('Hi! My name is ', voice.name); }); }, 1000);
speechSynthesis.getVoices()
returns an array. We could simply set the voice by doing:utterance.voice = speechSynthesis.getVoices()[11];
findIndex
, which is supported in browsers that also support the Web Synthesis API, so we’re all good.var agnesIndex = speechSynthesis.getVoices().findIndex(function (voice) { return voice.name === 'Agnes'; });Now that we’ve got the index of the voices array that Agnes’s voice is in, we can set that voice to be used by our utterance.
utterance.voice = speechSynthesis.getVoices()[agnesIndex]; utterance.text = 'It\'s me Agnes! I’m alive! Thank you.'; speechSynthesis.speak(utterance);No probs, Agnes. You scared me half to death with that loud voice of yours, though. Let’s turn you down a bit.
utterance.volume = 0.5;This sets the volume of Agnes’s voice to be half what it originally was, 0 being silent and 1 being the loudest. The parameters we can tweak don’t end there, however. Is the voice you’ve chosen speaking too slow or too fast? You can change the rate in which the voice reads out your piece of text by using the rate attribute.
utterance.rate = 0.8;
utterance.pitch = 0.2;
start
, end
, pause
, and resume
amongst others, allow us to call a function when said event happens. By
listening to the end event, we can call a function that starts another
voice speaking, thus providing the illusion of a conversation.setTimeout
function to make sure all possible voices have loaded.var voices = window.speechSynthesis.getVoices(), agnesUtterance = new SpeechSynthesisUtterance(), albertUtterance = new SpeechSynthesisUtterance(); agnesUtterance.voice = voices[11]; albertUtterance.voice = voices[12]; agnesUtterance.text = 'Hello Albert, I\'m Agnes'; albertUtterance.text = 'Hi Agnes, nice to meet you!';
onend
function call we set up Albert's reply like so. This means that when Agnes stops speaking, Albert will start.agnesUtterance.onend = function () { speechSynthesis.speak(albertUtterance); }
speechSynthesis.speak(agnesUtterance);
Comments
Post a Comment