AICon 上海站|90%日程已就绪,解锁Al未来! 了解详情
写点什么

用 80 行 JavaScript 代码构建自己的语音助手

  • 2020-07-17
  • 本文字数:3429 字

    阅读完需:约 11 分钟

用 80 行 JavaScript 代码构建自己的语音助手

在本教程中,我们将使用 80 行 JavaScript 代码在浏览器中构建一个虚拟助理(如 Siri 或 Google 助理)。你可以在这里测试这款应用程序,它将会听取用户的语音命令,然后用合成语音进行回复。

你所需要的是:


由于 Web Speech API 仍处于试验阶段,该应用程序只能在受支持的浏览器上运行:Chrome(版本 25 以上)和 Edge(版本 79 以上)。

我们需要构建哪些组件?

要构建这个 Web 应用程序,我们需要实现四个组件:


  1. 一个简单的用户界面,用来显示用户所说的内容和助理的回复。

  2. 将语音转换为文本。

  3. 处理文本并执行操作。

  4. 将文本转换为语音。

用户界面

第一步就是创建一个简单的用户界面,它包含一个按钮用来触发助理,一个用于显示用户命令和助理响应的 div、一个用于显示处理信息的 p 组件。


const startBtn = document.createElement("button");startBtn.innerHTML = "Start listening";const result = document.createElement("div");const processing = document.createElement("p");document.write("<body><h1>My Siri</h1><p>Give it a try with 'hello', 'how are you', 'what's your name', 'what time is it', 'stop', ... </p></body>");document.body.append(startBtn);document.body.append(result);document.body.append(processing);
复制代码

语音转文本

我们需要构建一个组件来捕获语音命令并将其转换为文本,以进行进一步处理。在本教程中,我们使用 Web Speech APISpeechRecognition。由于这个 API 只能在受支持的浏览器中使用,我们将显示警告信息并阻止用户在不受支持的浏览器中看到 Start 按钮。


const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;if (typeof SpeechRecognition === "undefined") {  startBtn.remove();  result.innerHTML = "<b>Browser does not support Speech API. Please download latest chrome.<b>";}
复制代码


我们需要创建一个 SpeechRecognition 的实例,可以设置一组各种属性来定制语音识别。在这个应用程序中,我们将 continuousinterimResults 设置为 true,以便实时显示语音文本。


const recognition = new SpeechRecognition();recognition.continuous = true;recognition.interimResults = true;
复制代码


我们添加一个句柄来处理来自语音 API 的 onresult 事件。在这个处理程序中,我们以文本形式显示用户的语音命令,并调用函数 process 来执行操作。这个 process 函数将在下一步实现。


function process(speech_text) {    return "....";}recognition.onresult = event => {   const last = event.results.length - 1;   const res = event.results[last];   const text = res[0].transcript;   if (res.isFinal) {      processing.innerHTML = "processing ....";      const response = process(text);      const p = document.createElement("p");      p.innerHTML = `You said: ${text} </br>Siri said: ${response}`;      processing.innerHTML = "";      result.appendChild(p);      // add text to speech later   } else {      processing.innerHTML = `listening: ${text}`;   }}
复制代码


我们还需要将 用户界面的 buttonrecognition 对象链接起来,以启动/停止语音识别。


let listening = false;toggleBtn = () => {   if (listening) {      recognition.stop();      startBtn.textContent = "Start listening";   } else {      recognition.start();      startBtn.textContent = "Stop listening";   }   listening = !listening;};startBtn.addEventListener("click", toggleBtn);
复制代码

处理文本并执行操作

在这一步中,我们将构建一个简单的会话逻辑并处理一些基本操作。助理可以回复“hello”、“what's your name?”、“how are you?”、提供当前时间的信息、“stop”听取或打开一个新的标签页来搜索它不能回答的问题。你可以通过使用一些 AI 库进一步扩展这个 process 函数,使助理更加智能。


function process(rawText) {   // remove space and lowercase text   let text = rawText.replace(/\s/g, "");   text = text.toLowerCase();   let response = null;   switch(text) {      case "hello":         response = "hi, how are you doing?"; break;      case "what'syourname":         response = "My name's Siri.";  break;      case "howareyou":         response = "I'm good."; break;      case "whattimeisit":         response = new Date().toLocaleTimeString(); break;      case "stop":         response = "Bye!!";         toggleBtn(); // stop listening   }   if (!response) {      window.open(`http://google.com/search?q=${rawText.replace("search", "")}`, "_blank");      return "I found some information for " + rawText;   }   return response;}
复制代码

文本转语音

在最后一步中,我们使用 Web Speech API 的 speechSynthesis 控制器为我们的助理提供语音。这个 API 简单明了。


speechSynthesis.speak(new SpeechSynthesisUtterance(response));
复制代码


就是这样!我们只用了 80 行代码就有了一个很酷的助理。程序的演示可以在这里找到。


// UI compconst startBtn = document.createElement("button");startBtn.innerHTML = "Start listening";const result = document.createElement("div");const processing = document.createElement("p");document.write("<body><h1>My Siri</h1><p>Give it a try with 'hello', 'how are you', 'what's your name', 'what time is it', 'stop', ... </p></body>");document.body.append(startBtn);document.body.append(result);document.body.append(processing);// speech to textconst SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;let toggleBtn = null;if (typeof SpeechRecognition === "undefined") {  startBtn.remove();  result.innerHTML = "<b>Browser does not support Speech API. Please download latest chrome.<b>";} else {  const recognition = new SpeechRecognition();  recognition.continuous = true;  recognition.interimResults = true;  recognition.onresult = event => {    const last = event.results.length - 1;    const res = event.results[last];    const text = res[0].transcript;    if (res.isFinal) {      processing.innerHTML = "processing ....";      const response = process(text);      const p = document.createElement("p");      p.innerHTML = `You said: ${text} </br>Siri said: ${response}`;      processing.innerHTML = "";      result.appendChild(p);      // text to speech      speechSynthesis.speak(new SpeechSynthesisUtterance(response));    } else {      processing.innerHTML = `listening: ${text}`;    }  }  let listening = false;  toggleBtn = () => {    if (listening) {      recognition.stop();      startBtn.textContent = "Start listening";    } else {      recognition.start();      startBtn.textContent = "Stop listening";    }    listening = !listening;  };  startBtn.addEventListener("click", toggleBtn);}// processorfunction process(rawText) {  let text = rawText.replace(/\s/g, "");  text = text.toLowerCase();  let response = null;  switch(text) {    case "hello":      response = "hi, how are you doing?"; break;    case "what'syourname":      response = "My name's Siri.";  break;    case "howareyou":      response = "I'm good."; break;    case "whattimeisit":      response = new Date().toLocaleTimeString(); break;    case "stop":      response = "Bye!!";      toggleBtn();  }  if (!response) {    window.open(`http://google.com/search?q=${rawText.replace("search", "")}`, "_blank");    return `I found some information for ${rawText}`;  }  return response;}×Drag and DropThe image will be downloaded
复制代码


作者介绍:


Tuan Nhu Dinh,Facebook 软件工程师。


原文链接:


https://medium.com/swlh/build-your-own-hi-siri-with-80-lines-of-javascript-code-653540c77502


2020-07-17 11:363789

评论 1 条评论

发布
用户头像
然而谷歌接口要翻墙
2020-07-28 13:16
回复
没有更多了
发现更多内容

开源堡垒机和免费商业堡垒机哪个用的更香?

行云管家

开源 网络安全 免费堡垒机

Elasticsearch之join关联查询及使用场景 | 京东云技术团队

京东科技开发者

数据库 elasticsearch sql join 企业号 5 月 PK 榜

什么是数字藏品|数字藏品系统开发源码?

Congge420

Gamefi很有潜力?分析链游gamefi系统开发源码!

Congge420

【参考设计】16芯串联电池包储能系统

元器件秋姐

芯片 电池 元器件 电源 驱动器

CFS第十二届财经峰会7月举行, 候选品牌:行云管家

行云管家

云计算 商业 财经峰会

首个机器学习实时特征平台测试基准论文被 VLDB 2023 录取

第四范式开发者社区

人工智能 机器学习 数据库 开源 特征

深度学习进阶篇-预训练模型[2]:Transformer-XL、Longformer、GPT原理、模型结构、应用场景、改进技巧等详细讲解

汀丶人工智能

人工智能 深度学习 nlp 预训练模型 Transformer

5人5月用容器技术保卫蓝天

华为云开发者联盟

云计算 后端 华为云 华为云开发者联盟 企业号 5 月 PK 榜

MobPush 合规指南

MobTech袤博科技

CMake常用命令大全:提高项目构建效率

小万哥

程序员 面试 后端 C/C++ cmake

一名开发者眼中的 TiDB 与 MySQL 的选择丨TiDB Community

PingCAP

MySQL 数据库 TiDB

构建高可用云原生应用,如何有效进行流量管理?

华为云开发者联盟

云原生 后端 华为云 华为云开发者联盟 企业号 5 月 PK 榜

索信达两大营销创新产品获官方认可,都有哪些创新亮点?

索信达控股

羊了个羊游戏|链游dapp系统开发方案

Congge420

公网对讲SDK——对讲应用场景

anyRTC开发者

音视频 视频会议 指挥调度 快对讲 公网对讲

为什么说财务共享是财务数智化转型的基石?

用友BIP

财务共享

[杂谈]百度飞浆环境配置

alexgaoyh

ubuntu gpu cuda cudnn PaddlePaddl

对话 ONES 联合创始人兼 CTO 冯斌:技术管理者如何打造一支自驱型团队?

万事ONES

1个Java程序员需要具备什么样的素质和能力才可以称得上高级工程师?

Java永远的神

程序员 后端 架构师 java面试 Java性能优化

3种分页列表缓存方式,速收藏~~

华为云开发者联盟

开发 华为云 华为云开发者联盟 企业号 5 月 PK 榜

文档关键信息提取形成知识图谱:基于NLP算法提取文本内容的关键信息生成信息图谱教程及码源(含pyltp安装使用教程)

汀丶人工智能

nlp 知识图谱 信息抽取 命名实体识别 pyltp

CST 电磁仿真计算时,为什么要关闭超线程?【操作教程】

思茂信息

cst cst使用教程 cst电磁仿真 cst仿真软件

又一开发者公布高分方案源代码,助力软件杯选手高效解题

飞桨PaddlePaddle

百度飞桨 中国软件杯

财务共享中心释放企业“数据”生产力

用友BIP

财务共享

前端微服务无界实践 | 京东云技术团队

京东科技开发者

微服务 前端 企业号 5 月 PK 榜 无界

成功加冕!用友大易获评2023最佳招聘管理软件供应商

用友BIP

招聘

Chrome分组插件

soap said

Chrome插件

用 80 行 JavaScript 代码构建自己的语音助手_语言 & 开发_Tuan Nhu Dinh_InfoQ精选文章