2019-05-01+Web+Designer+UK

(Brent) #1

Build a voice controlledUI


log.innerHTML= ‘Recognition error:
<br/>’+ ex.message;
}

15 .Clicktostop
Nowwhentheuserclickstostoptalking,thespeech
recognitionis stopped.Thebuttonis changedbackto
greenfromredwhiletalking.Theuserinterfaceis
updatedsothattheuseris informedthattheservicehas
stopped.Thespeakingvariableis settofalse,readytolet
theuserspeakagain.

} else {
recognizer.stop();
start.classList.toggle(‘stop’);
log.innerHTML = ‘Recognition stopped

log.innerHTML= ‘Recognition error:‘ +
event.message+ ‘<br />’ + log.innerHTML;
};

13 .Startspeaking!
Theeventlistenerhereis startedwhentheuserclicks
thebuttontostartspeaking.If theuseris notspeaking,
thenthebuttonchangescolourtoshowspeakinghas
started,thevariableforspeakingis settotrueandthe
‘interim’radiobuttonis checkedtoseeif thisis the
user’schoiceforinput.


start.addEventListener(‘click’, function() {
if (!speaking) {
speaking = true;
start.classList.toggle(‘stop’);
recognizer.interimResults = document.
querySelector(‘input[name=”recogniti
on-type”][value=”interim”]’).checked;

14 .Taketheinput
The‘tryandcatch’statementnowstartsthespeech
recognitionandtellstheuserthattheyshouldstart
speakingandthatwhentheyaredone,‘clickagainto stop’.
Thecatchwillpickuptheerrorandthrowthatintothe‘log’
divsothattheusercanunderstandwhatmightbewrong.


try {
recognizer.start();
log.innerHTML= ‘Startspeaking now
<br/>Click to stop’;
} catch (ex) {

Atthemoment,
browser support is
still low for speech
recognition. Checking
the stats for this on
Can I Use — caniuse.
com/#search=speech
—shows that there is
only around 65 percent
of browser uptake at
the moment, and that
is mainly confined to
Chrome and Opera.
This means that the
Speech Recognition
API is still very much in
the experimental zone
for your project. That
doesn’t mean you should
avoid this, as being on
the crest of a new way
to input for the web will
allow you to be ahead of
the curve, keeping your
skillset at the forefront
of what employers will
be looking for. Your
sites will be even more
accessible and better
equipped as further
mobile support comes
on board for this service.

Riding the
new wave

Tutorials


<br/>Click to speak’;
speaking= false;
}
});

16. Clear the text
The final code for this section is just a clear button
to remove the speech input text in case it is
wrongly interpreted. Save the file and test this in
your browser. You will be able to click the button to
speak into the computer and see the results.

clear.addEventListener(‘click’,function() {
transcription.textContent = ‘’;
});
}

16

tutorial ttttttttttttttttttttttttttttttttttttttttttttttttt 59
Free download pdf