首页 > 解决方案 > 如何在 kamiazya/ngx-speech-recognition 角度版本中完成录制后自动隐藏元素

问题描述

我有一个文本框和一个收听按钮,当您单击收听时,它将开始录制并附加到文本框,并且“正在收听..”文本将可见。现在我的要求是,当我在任何时间之间单击“停止收听”按钮时,录音应该停止并且“正在收听..”文本应该被隐藏。还假设我的录音在单击“停止收听..”按钮之前结束,“正在收听”..”文本应在自动完成录音后隐藏。这是我创建的演示https://stackblitz.com/edit/angular-wyphh6?file=src%2Fapp%2Fapp.component.ts。也请在下面找到代码。

app.component.html

<hello name="{{ name }}"></hello>

<p><input type="text" value="{{message}}"></p>
  <button

    (click)="listen()"
  >listen</button>
<p [hidden]="listening">Listening..</p>
<button [hidden]="listening">Stop Listening</button>

app.component.ts

import { Component } from '@angular/core';
import { RxSpeechRecognitionService, resultList, } from '@kamiazya/ngx-speech-recognition';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [ RxSpeechRecognitionService ]
})
export class AppComponent  {
  name = 'Angular';
  message = '';
  listening:boolean = true;
constructor(public service: RxSpeechRecognitionService) {


         }

     listen() {
       this.listening = false;
    this.service
      .listen()
      .pipe(resultList)
      .subscribe((list: SpeechRecognitionResultList) => {
        this.message = list.item(0).item(0).transcript;
        console.log('RxComponent:onresult', this.message, list);

      });

  }
  }

标签: angulartypescript

解决方案


我已经分叉了你的例子。要停止收听,请将takeUntil[operator] ( https://www.learnrxjs.io/operators/filtering/takeuntil.html ) 添加到管道中。使用布尔主题来销毁订阅。所以你的 app.component ts 变成了这样:

  ....
  stop = new Subject<boolean>();      
  listen() {
    this.listening = true;
    this.service
      .listen()
      .pipe(
        resultList,
        takeUntil(this.stop)
      )
      .subscribe((list: SpeechRecognitionResultList) => {
        const item = list.item(0);
        this.message = item.item(0).transcript;
        console.log("RxComponent:onresult", this.message, list);
        if (item.isFinal) { // this is set true when stream ends
          this.listening = false; // so its good time to set false
        }
      });
  }

  stopListening() {
    this.listening = false;
    this.stop.next(true);
  }

在您的视图中使用 *ngIfs 来隐藏和显示视图的必要部分:

  <button  
    (click)="listen()"
  >listen</button>
<p *ngIf="listening">Listening..</p>
<button *ngIf="listening" (click)="stopListening()">Stop Listening</button>

推荐阅读