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

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

WBOY
WBOY原创
2024-08-02 00:33:24837浏览

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