0

I have the following class:

class Voice{
    constructor(){
        const SpeechRecognition =  window.SpeechRecognition || window.webkitSpeechRecognition;
     
        let recognition = new SpeechRecognition(); //criou uma instance
  
        recognition.onstart = () => {  //inicia quando aperta espaço
            //console.log("starting listening, speak in microphone");
        }
  
        recognition.onspeechend = () => {  //inicia quando para de ouvir pessoa falando
            //console.log("stopped listening");
            recognition.stop();
        }
  
        recognition.onresult = (result) => {   //mostra no console o resultado da frase falada atraves de uma arrow function
        var word = result.results[0][0].transcript;
        console.log(word);
         }             
         recognition.start();
    }
}

export {Voice};

So, I would like to instantiate the class Voice in the main class and access the variable "word".

In the main class, I've tried:

  • function keyDown(e){  
        if (e.code=='Space'){
            let myWord = new Voice();
            console.log(myWord.word);
        }
    }
    
  • function keyDown(e){  
        if (e.code=='Space'){
            //voice();
            let myWord = new Voice();
            console.log(`${myWord.word}`);
        }
    } 
    

For both attempts, I got "undefined" as a result.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Jess
  • 1
  • 1
  • 1
    Instead of `var word =` you should be doing `this.word =`. Besides that, you have to wait for the result before trying to read the value. – code Feb 10 '23 at 22:47

0 Answers0