首頁  >  文章  >  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