So I have this speech to text typing feature that is triggered upon pressing a microphone icon. The feature works. My problem is that I want the same icon to do 2 things. 1st click it will start hearing for voice. 2nd click will stop hearing for voice. I basically want the function onclick
to alternate between 2 functions, Start and Stop. How do I do it?
Below is what I got currently. That only works to START the recording How do I fit recognition.stop()
into the same click function?
$('#micButton').on('click', function () {
recognition.start(); //this is to start recording
});
Below this is what I thought would work (it doesn't), to alternate between start and stop.
$('#micButton').on('click',
function () {
recognition.start();
},
function () {
recognition.stop();
}
);
To summarise, how do I get my onclick
to alternate between start and stop?
You'll need a flag of some sort to check to see if voice is currently being listened for:
let currentlyListening = false;
$('#micButton').on('click', function () {
if (!currentlyListening) {
recognition.start(); //this is to start recording
} else {
recognition.stop();
}
currentlyListening = !currentlyListening;
});
It'd probably be good to also provide an indicator to the user the current state as well, if recognition
doesn't already do that - eg, change or add an image that shows a red dot while currentlyListening
is true
.
Could set a data tag or a class to determine if it's being used or not.
// SEEING AS YOU'RE USING JQUERY
$('#micButton').on('click', function () {
if($(this).data('active') == false) {
recognition.start();
$(this).data('active', true);
} else {
recognition.stop();
$(this).data('active', false);
}
}
Ternary operator can be used as well!)
$('#micButton').on('click', function () {
recognition[ this.listening ? "stop" : "start" ]();
this.listening = !this.listening;
});
Nearly the same thing, as @CertainPerformance answer, but storing the true / false flag in the clicked element object.
First click: this.listening == undefined (false)
, → recognition.start();
Second click: this.listening == true
, → recognition.stop();
And so on.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.