Neste post eu irei mostrar como fazer uma implementação simples para movimentar objetos na tela utilizando o speech to text com Javascript Vanilla.

Objetivos

Criar um algoritmo simples com apenas x linhas que possibilite movimentar um objeto pela tela e trocar a cor deste objeto.

Algoritmo


<!--JavaScript - Move Object with Arrow Keys using JavaScript Function.-->
<html>
    <head>
        <title>JavaScript - Move Object with Arrow Keys using JavaScript Function.</title>
        <style>
          #myObj {
            width: 200px;
            height: 200px;
            background: #ff0000;
            border-radius: 50%;
          }
        </style>
        <script type="text/javascript">

            var objImage = null;
            function init() {
                objImage = document.getElementById("myObj");
                objImage.style.position = "relative";
                objImage.style.left = "0px";
                objImage.style.top = "0px";
            }

            function getKeyAndMove(e) {
                var key_code = e.which || e.keyCode;
                switch (key_code) {
                    case 37: //left arrow key
                        moveLeft();
                        break;
                    case 38: //Up arrow key
                        moveUp();
                        break;
                    case 39: //right arrow key
                        moveRight();
                        break;
                    case 40: //down arrow key
                        moveDown();
                        break;
                }
            }
            function moveLeft() {
                objImage.style.left = parseInt(objImage.style.left) - 100 + "px";
            }
            function moveUp() {
                objImage.style.top = parseInt(objImage.style.top) - 100 + "px";
            }
            function moveRight() {
                objImage.style.left = parseInt(objImage.style.left) + 100 + "px";
            }
            function moveDown() {
                objImage.style.top = parseInt(objImage.style.top) + 100   + "px";
            }


            window.onload = init;

        </script>
    </head>

    <body onkeydown="getKeyAndMove(event)">

        <p id="output"></p>
        <button id="start"> Start! </button>


        <div id="myObj"> </div>

        <script>
          (() => {
            
            const startBtn = document.querySelector('#start');
            const output = document.querySelector('#output');

            // 
            function getKeyAndMove(e) {
                var key_code = e.which || e.keyCode;
                switch (key_code) {
                    case 37: //left arrow key
                        moveLeft();
                        break;
                    case 38: //Up arrow key
                        moveUp();
                        break;
                    case 39: //right arrow key
                        moveRight();
                        break;
                    case 40: //down arrow key
                        moveDown();
                        break;
                }
            }
            function moveLeft() {
                objImage.style.left = parseInt(objImage.style.left) - 100 + "px";
            }
            function moveUp() {
                objImage.style.top = parseInt(objImage.style.top) - 100 + "px";
            }
            function moveRight() {
                objImage.style.left = parseInt(objImage.style.left) + 100 + "px";
            }
            function moveDown() {
                objImage.style.top = parseInt(objImage.style.top) + 100   + "px";
            }
            // 
    
            function start() {
              
              const recognition = new webkitSpeechRecognition();

              recognition.interimResults = true;
              recognition.lang = "pt-BR";
              recognition.continuous = true;
              recognition.start();


              recognition.onresult = function(event) {
                for (let i = event.resultIndex; i < event.results.length; i++) {
                  if (event.results[i].isFinal) {
                    const content = event.results[i][0].transcript.trim();
                    output.textContent = content;
                    console.log(content);
                    document.getElementById("myObj").style.backgroundColor= content;

                    switch (content) {
                        case 'esquerda': //left arrow key
                            moveLeft();
                            break;
                        case 'duas esquerdas': //left arrow key
                            moveLeft();
                            moveLeft();
                            break;
                        case 'cima': //Up arrow key
                            moveUp();
                            break;
                        case 'direita': //right arrow key
                            moveRight();
                            break;
                        case 'duas direita': //right arrow key
                            moveRight();
                            moveRight();
                            break;
                        case 'baixo': //down arrow key
                            moveDown();
                            break;
                    }


                  }
                }
              };
            };
            startBtn.addEventListener('click', () => start());
          })();

        </script>

    <!-- Code injected by live-server -->
<script type="text/javascript">
	// <![CDATA[  <-- For SVG support
	if ('WebSocket' in window) {
		(function () {
			function refreshCSS() {
				var sheets = [].slice.call(document.getElementsByTagName("link"));
				var head = document.getElementsByTagName("head")[0];
				for (var i = 0; i < sheets.length; ++i) {
					var elem = sheets[i];
					var parent = elem.parentElement || head;
					parent.removeChild(elem);
					var rel = elem.rel;
					if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
						var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
						elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
					}
					parent.appendChild(elem);
				}
			}
			var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
			var address = protocol + window.location.host + window.location.pathname + '/ws';
			var socket = new WebSocket(address);
			socket.onmessage = function (msg) {
				if (msg.data == 'reload') window.location.reload();
				else if (msg.data == 'refreshcss') refreshCSS();
			};
			if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) {
				console.log('Live reload enabled.');
				sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true);
			}
		})();
	}
	else {
		console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.');
	}
	// ]]>
</script></body>
</html>

Repositório do Github

Para baixar o código você pode acessar o meu Github através do link:
https://github.com/jaccon/move-objects-using-voice

Demonstração do script em funcionamento