{"id":19100795,"url":"https://github.com/Azure-Samples/AzureSpeechReactSample","last_synced_at":"2025-04-18T18:30:58.212Z","repository":{"id":43319905,"uuid":"340457087","full_name":"Azure-Samples/AzureSpeechReactSample","owner":"Azure-Samples","description":"This sample shows how to integrate the Azure Speech service into a sample React application. This sample shows design pattern examples for authentication token exchange and management, as well as capturing audio from a microphone or file for speech-to-text conversions.","archived":false,"fork":false,"pushed_at":"2023-10-23T16:51:38.000Z","size":211,"stargazers_count":111,"open_issues_count":6,"forks_count":75,"subscribers_count":17,"default_branch":"main","last_synced_at":"2024-04-11T17:02:22.853Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Azure-Samples.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2021-02-19T18:33:20.000Z","updated_at":"2024-04-10T15:27:14.000Z","dependencies_parsed_at":"2023-10-20T18:13:19.838Z","dependency_job_id":null,"html_url":"https://github.com/Azure-Samples/AzureSpeechReactSample","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2FAzureSpeechReactSample","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2FAzureSpeechReactSample/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2FAzureSpeechReactSample/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2FAzureSpeechReactSample/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Azure-Samples","download_url":"https://codeload.github.com/Azure-Samples/AzureSpeechReactSample/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223783096,"owners_count":17201904,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T03:53:00.194Z","updated_at":"2025-04-18T18:30:58.196Z","avatar_url":"https://github.com/Azure-Samples.png","language":"JavaScript","funding_links":[],"categories":["others"],"sub_categories":[],"readme":"# React Speech service sample app\n\nThis sample shows how to integrate the Azure Speech service into a sample React application. This sample shows design pattern examples for authentication token exchange and management, as well as capturing audio from a microphone or file for speech-to-text conversions.\n\n## Prerequisites\n\n1. This article assumes that you have an Azure account and Speech service subscription. If you don't have an account and subscription, [try the Speech service for free](https://docs.microsoft.com/azure/cognitive-services/speech-service/overview#try-the-speech-service-for-free).\n1. Ensure you have [Node.js](https://nodejs.org/en/download/) installed.\n\n## How to run the app\n\n1. Clone this repo, then change directory to the project root and run `npm install` to install dependencies.\n1. Add your Azure Speech key and region to the `.env` file, replacing the placeholder text.\n1. To run the Express server and React app together, run `npm run dev`.\n\n## Change recognition language\n\nTo change the source recognition language, change the locale strings in `App.js` lines **32** and **66**, which sets the recognition language property on the `SpeechConfig` object.\n\n```javascript\nspeechConfig.speechRecognitionLanguage = 'en-US'\n```\n\nFor a full list of supported locales, see the [language support article](https://docs.microsoft.com/azure/cognitive-services/speech-service/language-support#speech-to-text).\n\n## Speech-to-text from microphone\n\nTo convert speech-to-text using a microphone, run the app and then click **Convert speech to text from your mic.**. This will prompt you for access to your microphone, and then listen for you to speak. The following function `sttFromMic` in `App.js` contains the implementation.\n\n```javascript\nasync sttFromMic() {\n    const tokenObj = await getTokenOrRefresh();\n    const speechConfig = speechsdk.SpeechConfig.fromAuthorizationToken(tokenObj.authToken, tokenObj.region);\n    speechConfig.speechRecognitionLanguage = 'en-US';\n    \n    const audioConfig = speechsdk.AudioConfig.fromDefaultMicrophoneInput();\n    const recognizer = new speechsdk.SpeechRecognizer(speechConfig, audioConfig);\n\n    this.setState({\n        displayText: 'speak into your microphone...'\n    });\n\n    recognizer.recognizeOnceAsync(result =\u003e {\n        let displayText;\n        if (result.reason === ResultReason.RecognizedSpeech) {\n            displayText = `RECOGNIZED: Text=${result.text}`\n        } else {\n            displayText = 'ERROR: Speech was cancelled or could not be recognized. Ensure your microphone is working properly.';\n        }\n\n        this.setState({\n            displayText: displayText\n        });\n    });\n}\n```\n\nRunning speech-to-text from a microphone is done by creating an `AudioConfig` object and using it with the recognizer.\n\n```javascript\nconst audioConfig = speechsdk.AudioConfig.fromDefaultMicrophoneInput();\nconst recognizer = new speechsdk.SpeechRecognizer(speechConfig, audioConfig);\n```\n\n## Speech-to-text from file\n\nTo convert speech-to-text from an audio file, run the app and then click **Convert speech to text from an audio file.**. This will open a file browser and allow you to select an audio file. The following function `fileChange` is bound to an event handler that detects the file change. \n\n```javascript\nasync fileChange(event) {\n    const audioFile = event.target.files[0];\n    console.log(audioFile);\n    const fileInfo = audioFile.name + ` size=${audioFile.size} bytes `;\n\n    this.setState({\n        displayText: fileInfo\n    });\n\n    const tokenObj = await getTokenOrRefresh();\n    const speechConfig = speechsdk.SpeechConfig.fromAuthorizationToken(tokenObj.authToken, tokenObj.region);\n    speechConfig.speechRecognitionLanguage = 'en-US';\n\n    const audioConfig = speechsdk.AudioConfig.fromWavFileInput(audioFile);\n    const recognizer = new speechsdk.SpeechRecognizer(speechConfig, audioConfig);\n\n    recognizer.recognizeOnceAsync(result =\u003e {\n        let displayText;\n        if (result.reason === ResultReason.RecognizedSpeech) {\n            displayText = `RECOGNIZED: Text=${result.text}`\n        } else {\n            displayText = 'ERROR: Speech was cancelled or could not be recognized. Ensure your microphone is working properly.';\n        }\n\n        this.setState({\n            displayText: fileInfo + displayText\n        });\n    });\n}\n```\n\nYou need the audio file as a JavaScript [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) object, so you can grab it directly off the event target using `const audioFile = event.target.files[0];`. Next, you use the file to create the `AudioConfig` and then pass it to the recognizer.\n\n```javascript\nconst audioConfig = speechsdk.AudioConfig.fromWavFileInput(audioFile);\nconst recognizer = new speechsdk.SpeechRecognizer(speechConfig, audioConfig);\n```\n\n## Token exchange process\n\nThis sample application shows an example design pattern for retrieving and managing tokens, a common task when using the Speech JavaScript SDK in a browser environment. A simple Express back-end is implemented in the same project under `server/index.js`, which abstracts the token retrieval process. \n\nThe reason for this design is to prevent your speech key from being exposed on the front-end, since it can be used to make calls directly to your subscription. By using an ephemeral token, you are able to protect your speech key from being used directly. To get a token, you use the Speech REST API and make a call using your speech key and region. In the Express part of the app, this is implemented in `index.js` behind the endpoint `/api/get-speech-token`, which the front-end uses to get tokens. \n\n```javascript\napp.get('/api/get-speech-token', async (req, res, next) =\u003e {\n    res.setHeader('Content-Type', 'application/json');\n    const speechKey = process.env.SPEECH_KEY;\n    const speechRegion = process.env.SPEECH_REGION;\n\n    if (speechKey === 'paste-your-speech-key-here' || speechRegion === 'paste-your-speech-region-here') {\n        res.status(400).send('You forgot to add your speech key or region to the .env file.');\n    } else {\n        const headers = { \n            headers: {\n                'Ocp-Apim-Subscription-Key': speechKey,\n                'Content-Type': 'application/x-www-form-urlencoded'\n            }\n        };\n\n        try {\n            const tokenResponse = await axios.post(`https://${speechRegion}.api.cognitive.microsoft.com/sts/v1.0/issueToken`, null, headers);\n            res.send({ token: tokenResponse.data, region: speechRegion });\n        } catch (err) {\n            res.status(401).send('There was an error authorizing your speech key.');\n        }\n    }\n});\n```\n\nIn the request, you create a `Ocp-Apim-Subscription-Key` header, and pass your speech key as the value. Then you make a request to the **issueToken** endpoint for your region, and an authorization token is returned. In a production application, this endpoint returning the token should be *restricted by additional user authentication* whenever possible. \n\nOn the front-end, `token_util.js` contains the helper function `getTokenOrRefresh` that is used to manage the refresh and retrieval process. \n\n```javascript\nexport async function getTokenOrRefresh() {\n    const cookie = new Cookie();\n    const speechToken = cookie.get('speech-token');\n\n    if (speechToken === undefined) {\n        try {\n            const res = await axios.get('/api/get-speech-token');\n            const token = res.data.token;\n            const region = res.data.region;\n            cookie.set('speech-token', region + ':' + token, {maxAge: 540, path: '/'});\n\n            console.log('Token fetched from back-end: ' + token);\n            return { authToken: token, region: region };\n        } catch (err) {\n            console.log(err.response.data);\n            return { authToken: null, error: err.response.data };\n        }\n    } else {\n        console.log('Token fetched from cookie: ' + speechToken);\n        const idx = speechToken.indexOf(':');\n        return { authToken: speechToken.slice(idx + 1), region: speechToken.slice(0, idx) };\n    }\n}\n```\n\nThis function uses the `universal-cookie` library to store and retrieve the token from local storage. It first checks to see if there is an existing cookie, and in that case it returns the token without hitting the Express back-end. If there is no existing cookie for a token, it makes the call to `/api/get-speech-token` to fetch a new one. Since we need both the token and its corresponding region later, the cookie is stored in the format `token:region` and upon retrieval is spliced into each value.\n\nTokens for the service expire after 10 minutes, so the sample uses the `maxAge` property of the cookie to act as a trigger for when a new token needs to be generated. It is reccommended to use 9 minutes as the expiry time to act as a buffer, so we set `maxAge` to **540 seconds**.\n\nIn `App.js` you use `getTokenOrRefresh` in the functions for speech-to-text from a microphone, and from a file. Finally, use the `SpeechConfig.fromAuthorizationToken` function to create an auth context using the token.\n\n```javascript\nconst tokenObj = await getTokenOrRefresh();\nconst speechConfig = speechsdk.SpeechConfig.fromAuthorizationToken(tokenObj.authToken, tokenObj.region);\n```\n\nIn many other Speech service samples, you will see the function `SpeechConfig.fromSubscription` used instead of `SpeechConfig.fromAuthorizationToken`, but by **avoiding the usage** of `fromSubscription` on the front-end, you prevent your speech subscription key from becoming exposed, and instead utilize the token authentication process. `fromSubscription` is safe to use in a Node.js environment, or in other Speech SDK programming languages when the call is made on a back-end, but it is best to avoid using in a browser-based JavaScript environment.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2FAzureSpeechReactSample","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAzure-Samples%2FAzureSpeechReactSample","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2FAzureSpeechReactSample/lists"}