angular - 如何在 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);
});
}
}
解决方案
我已经分叉了你的例子。要停止收听,请将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>
推荐阅读
- http - 某些服务如何跟踪每个收件人打开的电子邮件?
- android - 在动态加载的外部类中使用本机库(带反射)
- loops - 每行的sas循环
- reactjs - 如何在 Apollo Query Render Props 中调用 setState?
- javascript - javascript:如何拆分包含两位数整数的字符串?
- android - 为什么我在聊天应用程序中出现超时?
- python-2.7 - 每当我尝试使用 pip 安装模块时,都会发生错误
- python - 无法在生产服务器中连接 Amazon RDS,但在本地服务器上连接
- raspberry-pi - 树莓派 hcitool 设置从 csv 文件导入的广告数据包
- reactjs - 多个请求发出时如何处理刷新令牌?