使用 JavaScript 进行语音识别
封面图片来源:dribbble
前段时间,语音识别 API被添加到规范中,我们在 Chrome、Safari、百度、android webview、iOS safari、三星互联网和 Kaios 浏览器上获得了部分支持(详细请参阅浏览器支持)。
免责声明:此实现在 Opera 中不起作用(因为它不支持构造函数),在 FireFox 中也不起作用(因为它不支持其中任何一个),所以如果您使用其中之一,我建议您使用 Chrome - 或任何其他兼容的浏览器 - 如果您想尝试一下。
语音识别代码和PoC
编辑:我意识到由于某种原因它在嵌入时无法工作,所以这里是直接打开它的链接。
我所做的实现目前支持英语和西班牙语,只是为了展示。
快速说明和功能概述:
- 从下拉菜单中选择一种语言。
- 点击麦克风图标,它将开始录音(您会注意到一个奇怪的动画)。
- 一旦你完成一个句子,它就会将其写入框中。
- 当您想停止录音时,只需再次按下麦克风(动画停止)。
- 您还可以点击该框来复制剪贴板中的文本。
使用 JavaScript 在浏览器中进行语音识别 - 关键代码块:
/* Check whether the SpeechRecognition or the webkitSpeechRecognition API is available on window and reference it */
const recognitionSvc = window.SpeechRecognition || window.webkitSpeechRecognition;
// Instantiate it
const recognition = new recognitionSvc();
/* Set the speech recognition to continuous so it keeps listening to whatever you say. This way you can record long texts, conversations and so on. */
recognition.continuous = true;
/* Sets the language for speech recognition. It uses IETF tags, ISO 639-1 like en-GB, en-US, es-ES and so on */
recognition.lang = 'en-GB';
// Start the speech recognition
recognition.start();
// Event triggered when it gets a match
recognition.onresult = (event) => {
// iterate through speech recognition results
for (const result of event.results) {
// Print the transcription to the console
console.log(`${result[0].transcript}`);
}
}
// Stop the speech recognition
recognition.stop();
此实现目前支持以下语言的语音识别:
- 英文
- 英文
- es-ES
- 去-DE
- 脱甲基
- fr-FR
如果您希望我添加对更多语言的支持,请在评论部分告诉我,我会立即更新它,以便您可以使用自己的语言进行测试😁
今天就到这里,希望你喜欢,我确实喜欢
文章来源:https://dev.to/joelbonetr/speech-recognition-with-javascript-59g1