首页 web前端 js教程 将具有语法支持的语音识别添加到您的 Angular 应用程序中

将具有语法支持的语音识别添加到您的 Angular 应用程序中

Aug 02, 2024 am 12:33 AM

Adding Speech Recognition with Grammar Support to Your Angular Application

语音识别允许用户使用语音输入文本或命令,从而极大地增强 Web 应用程序中的用户交互。在本教程中,我将向您展示如何将语音识别集成到 Angular 应用程序中,并通过语法支持来增强它。

先决条件

  • Angular 的基础知识。
  • 已安装 Angular CLI。
  • 现有的 Angular 项目或使用 ng new voice-recognition-app 创建一个新项目。

第 1 步:设置语音识别服务

首先,我们需要创建一个服务来处理语音识别。该服务将使用 Web Speech API 的 webkitSpeechRecognition 和 SpeechGrammarList。

创建新服务:
ng 生成语音识别服务
现在,更新生成的语音识别.service.ts:

import { Injectable, NgZone } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class SpeechRecognitionService {
  recognition: any;
  isListening: boolean = false;

  constructor(private zone: NgZone) {
    const { webkitSpeechRecognition, webkitSpeechGrammarList }: IWindow = window as any;
    this.recognition = new webkitSpeechRecognition();
    this.recognition.continuous = false;
    this.recognition.interimResults = false;
    this.recognition.lang = 'en-US';

    const grammar = '#JSGF V1.0; grammar colors; public <color> = red | green | blue | yellow ;';
    const speechRecognitionList = new webkitSpeechGrammarList();
    speechRecognitionList.addFromString(grammar, 1);
    this.recognition.grammars = speechRecognitionList;
  }

  startListening(): Promise<string> {
    return new Promise((resolve, reject) => {
      if (this.isListening) {
        reject('Already listening');
      }

      this.isListening = true;

      this.recognition.onresult = (event: any) => {
        this.zone.run(() => {
          const result = event.results[0][0].transcript;
          this.stopListening();
          resolve(result);
        });
      };

      this.recognition.onerror = (event: any) => {
        this.zone.run(() => {
          this.isListening = false;
          reject(event.error);
        });
      };

      this.recognition.onend = () => {
        this.zone.run(() => {
          this.isListening = false;
        });
      };

      this.recognition.start();
    });
  }

  stopListening(): void {
    if (this.isListening) {
      this.recognition.stop();
      this.isListening = false;
    }
  }
}

interface IWindow extends Window {
  webkitSpeechRecognition: any;
  webkitSpeechGrammarList: any;
}

登录后复制

第 2 步:创建组件

接下来,我们将创建一个组件来利用我们的语音识别服务。该组件将有一个文本区域和一个麦克风图标。当用户单击图标时,语音识别将开始,识别的文本将添加到文本区域。
更新app.component.ts:

import { Component } from '@angular/core';
import { SpeechRecognitionService } from './speech-recognition.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  note: string = '';
  isListening: boolean = false;

  constructor(private speechRecognitionService: SpeechRecognitionService) {}

  toggleListening() {
    if (this.isListening) {
      this.speechRecognitionService.stopListening();
      this.isListening = false;
    } else {
      this.isListening = true;
      this.speechRecognitionService.startListening().then(
        (result: string) => {
          this.note = result;
          this.isListening = false;
        },
        (error: any) => {
          console.error('Speech recognition error', error);
          this.isListening = false;
        }
      );
    }
  }
}
登录后复制

第 3 步:更新模板

在模板中,我们将点击事件绑定到我们的切换方法,并使用 Angular 的 ngClass 指令在麦克风监听时添加发光效果。

更新app.component.html:

<div class="textarea-container">
  <textarea
    maxlength="150"
    class="form-control"
    id="message-text"
    rows="3"
    [(ngModel)]="note"
  ></textarea>
  <i
    (click)="toggleListening()"
    class="mdi mdi-microphone mic-icon"
    [ngClass]="{ 'glow': isListening }"
  ></i>
</div>
登录后复制

第 4 步:添加样式

添加一些样式来定位麦克风图标并在收听时添加发光效果。

更新app.component.css:

.textarea-container {
  position: relative;
  display: inline-block;
}

.textarea-container textarea {
  width: 100%;
  box-sizing: border-box;
}

.mic-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 24px;
  color: #333;
  transition: box-shadow 0.3s ease;
}

.mic-icon.glow {
  box-shadow: 0 0 10px 2px rgba(255, 0, 0, 0.8);
}

登录后复制

第 5 步:测试您的应用程序

使用以下命令运行 Angular 应用程序:
服务

在浏览器中导航至 http://localhost:4200/。您应该看到带有麦克风图标的文本区域。当您单击该图标时,它将开始监听,并且该图标会发光。说出语法列表中的一种颜色(红、绿、蓝、黄),识别出的颜色将添加到文本区域。

结论

您已成功将具有语法支持的语音识别添加到您的 Angular 应用程序中。可以扩展此功能以识别更复杂的命令并与应用程序中的各种功能无缝集成。尝试不同的语法和语音识别设置,看看什么最适合您的用例。
在 linkedin 上关注我
快乐编码!

以上是将具有语法支持的语音识别添加到您的 Angular 应用程序中的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何创建和发布自己的JavaScript库? 如何创建和发布自己的JavaScript库? Mar 18, 2025 pm 03:12 PM

文章讨论了创建,发布和维护JavaScript库,专注于计划,开发,测试,文档和促销策略。

如何在浏览器中优化JavaScript代码以进行性能? 如何在浏览器中优化JavaScript代码以进行性能? Mar 18, 2025 pm 03:14 PM

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

如何使用浏览器开发人员工具有效调试JavaScript代码? 如何使用浏览器开发人员工具有效调试JavaScript代码? Mar 18, 2025 pm 03:16 PM

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

如何使用源地图调试缩小JavaScript代码? 如何使用源地图调试缩小JavaScript代码? Mar 18, 2025 pm 03:17 PM

本文说明了如何使用源地图通过将其映射回原始代码来调试JAVASCRIPT。它讨论了启用源地图,设置断点以及使用Chrome DevTools和WebPack之类的工具。

如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? 如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? Apr 04, 2025 pm 05:09 PM

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

console.log输出结果差异:两次调用为何不同? console.log输出结果差异:两次调用为何不同? Apr 04, 2025 pm 05:12 PM

深入探讨console.log输出差异的根源本文将分析一段代码中console.log函数输出结果的差异,并解释其背后的原因。�...

See all articles