h5 SpeechRecognition代码如何写
时间: 2023-12-06 15:44:59 浏览: 108
使用HTML5的SpeechRecognition API,可以通过以下步骤实现语音识别:
1. 创建一个SpeechRecognition对象:
```
const recognition = new SpeechRecognition();
```
2. 设置recognition的一些属性:
```
recognition.lang = 'en-US'; // 设置语言,可以是任何支持的语言
recognition.interimResults = false; // 是否返回中间结果
recognition.maxAlternatives = 1; // 最大备选项数
```
3. 监听recognition的事件:
```
recognition.onresult = (event) => {
const result = event.results[0][0].transcript;
console.log(result); // 输出识别结果
};
recognition.onerror = (event) => {
console.log(event.error); // 输出错误信息
};
```
4. 开始语音识别:
```
recognition.start();
```
完整代码示例:
```
const recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onresult = (event) => {
const result = event.results[0][0].transcript;
console.log(result);
};
recognition.onerror = (event) => {
console.log(event.error);
};
recognition.start();
```
阅读全文