ホームページ  >  記事  >  ウェブフロントエンド  >  文法サポートを備えた音声認識を 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 speech-recognition-app を使用して新しいプロジェクトを作成します。

ステップ 1: 音声認識サービスをセットアップする

まず、音声認識を処理するサービスを作成する必要があります。このサービスは、Web Speech API の webkitSpeechRecognition および SpeechGrammarList を使用します。

新しいサービスを作成します:
サービス音声認識を生成します
ここで、生成された speech-recognition.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 アプリケーションを実行します。
サーブはNG

ブラウザで http://localhost:4200/ に移動します。テキストエリアにマイクアイコンが表示されるはずです。アイコンをクリックするとリスニングが開始され、アイコンが光ります。文法リストから色 (赤、緑、青、黄) を読み上げると、認識された色がテキストエリアに追加されます。

結論

これで、文法サポートを備えた音声認識が Angular アプリケーションに追加されました。この機能を拡張して、より複雑なコマンドを認識し、アプリケーションのさまざまな機能とシームレスに統合できます。さまざまな文法と音声認識設定を試して、ユースケースに最適なものを確認してください。
linkedin でフォローしてください
コーディングを楽しんでください!

以上が文法サポートを備えた音声認識を Angular アプリケーションに追加するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。