You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Create an AudioConfig object from microphone stream
Create a SpeechRecognizer object
Simple Express Server
require('dotenv').config();constexpress=require('express');constaxios=require('axios');constbodyParser=require('body-parser');constpino=require('express-pino-logger')();constapp=express();app.use(bodyParser.urlencoded({extended: false}));app.use(pino);app.get('/api/get-speech-token',async(req,res,next)=>{res.setHeader('Content-Type','application/json');constspeechKey=process.env.SPEECH_KEY;constspeechRegion=process.env.SPEECH_REGION;if(speechKey==='paste-your-speech-key-here'||speechRegion==='paste-your-speech-region-here'){res.status(400).send('You forgot to add your speech key or region to the .env file.');}else{constheaders={headers: {'Ocp-Apim-Subscription-Key': speechKey,'Content-Type': 'application/x-www-form-urlencoded'}};try{consttokenResponse=awaitaxios.post(`https://${speechRegion}.api.cognitive.microsoft.com/sts/v1.0/issueToken`,null,headers);res.send({token: tokenResponse.data,region: speechRegion});}catch(err){res.status(401).send('There was an error authorizing your speech key.');}}});app.listen(3001,()=>console.log('Express server is running on localhost:3001'));
Token Utility Function
importaxiosfrom'axios';importCookiefrom'universal-cookie';exportasyncfunctiongetTokenOrRefresh(){constcookie=newCookie();constspeechToken=cookie.get('speech-token');if(speechToken===undefined){try{constres=awaitaxios.get('/api/get-speech-token');consttoken=res.data.token;constregion=res.data.region;cookie.set('speech-token',region+':'+token,{maxAge: 540,path: '/'});console.log('Token fetched from back-end: '+token);return{authToken: token,region: region};}catch(err){console.log(err.response.data);return{authToken: null,error: err.response.data};}}else{console.log('Token fetched from cookie: '+speechToken);constidx=speechToken.indexOf(':');return{authToken: speechToken.slice(idx+1),region: speechToken.slice(0,idx)};}}