【问题标题】:How do I get my text from speech rendered to Angular Html?如何从呈现为 Angular Html 的语音中获取文本?
【发布时间】:2022-01-29 23:42:57
【问题描述】:

我正在尝试向我的 app.component.html 呈现一个名为“this.text”的变量。我可以通过一个名为“recognition.onresult”的函数更改“this.text”,但它不会呈现或更改到屏幕上。 “recognition.onresult”函数最初在“speech.ts”文件中,但在组件文件中我得到了更好的结果。

app.component.html

<h1>{{text}}</h1>

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { SocketService } from "./socket.service";
import recognition from './speech';

...

export class AppComponent implements OnInit, OnDestroy {

    text:any = 'hi';

      public constructor(private socket: SocketService) {
    }
    getText(text:any){
      console.log(text)
      this.text = text
     if (text === "what's today's date"){
       alert("none ya")
       this.text = "None ya"
     }
    }
    
    ngOnInit(){
      recognition.onresult = (event:any) => {
        // get the results of the speech recognition
        const resultIndex = event.resultIndex
        const result = event.results[resultIndex][0].transcript
        this.getText(result.toString())
        // perform actions based on transcript and level of confidence
      }
        this.socket.getEventListener().subscribe(event => {
          recognition.start();
            if(event.type == "message") {
                let data = event.data.content;
                if(event.data.sender) {
                    data = event.data.sender + ": " + data;
                }
            }
            if(event.type == "close") {
            }
            if(event.type == "open") {
                
              }
        });
    }
...
}

speech.ts

declare const webkitSpeechRecognition: any;

var SpeechRecognition = webkitSpeechRecognition;
let recognition = new SpeechRecognition()
recognition.lang = "en";
recognition.continuous = true

recognition.onstart = function () {
  // actions to be performed when speech recognition starts
  console.log(recognition)
};

recognition.onspeechend = function () {
  // stop speech recognition when the person stops talking
  recognition.stop();
}



export default recognition



【问题讨论】:

  • 你所拥有的应该可以工作。根据您的描述,您的 Angular 实例不会对组件模型所做的更改做出反应,这意味着它已损坏。您能否创建一个 runnable minimal reproducible example 以确保它重现您在 codesandbox.io 或类似网站上的错误?根据您发布的内容,无法知道您的应用程序出了什么问题。这可能是一个配置问题,也可能是一些非常琐碎的事情,比如必须重新启动服务。

标签: javascript angular speech-recognition speech-to-text


【解决方案1】:

如果你的逻辑没问题,那么你可以只使用 ChangeDetectorRef,它将显式标记更改并重新渲染视图。

import { ChangeDetectorRef } from '@angular/core';
...

constructor(private cdr:ChangeDetectorRef) {
   ...
}

更新文本后在 getText() 函数中使用更改检测。

this.cdr.detectChanges();

这应该反映 HTML 的变化。

【讨论】:

    猜你喜欢
    • 2011-03-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2015-10-08
    相关资源
    最近更新 更多