Angular 实现发送语音
时间: 2023-12-06 21:02:12 浏览: 25
Angular 可以使用 Web Speech API 实现发送语音的功能。以下是一个示例:
1. 首先在 HTML 文件中添加一个按钮和一个文本框,以及一个包含语音识别结果的 div:
```html
<input type="text" [(ngModel)]="message">
<button (click)="startRecognition()">发送语音</button>
<div>{{speechResult}}</div>
```
2. 在组件文件中导入 Web Speech API,并定义一个 SpeechRecognition 对象:
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message: string = '';
speechResult: string = '';
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'zh-CN';
```
3. 编写 startRecognition 方法,该方法会启动语音识别,并将结果显示在 speechResult 中:
```typescript
startRecognition() {
this.recognition.start();
let speechResult = '';
this.recognition.onresult = function(event) {
speechResult = event.results[0][0].transcript;
}
this.recognition.onend = function() {
this.speechResult = speechResult;
}.bind(this);
}
}
```
4. 当用户点击发送语音按钮时,startRecognition 方法会启动语音识别,并将结果显示在 speechResult 中。
注意:这个示例只适用于使用 Chrome 浏览器的用户。其他浏览器可能需要使用不同的 API。