SpeechSynthesisUtterance speak如何返回正在读的字
1SpeechSynthesisUtterance speak如何返回正在读的字
SpeechSynthesisUtterance 的 speak 方法没有返回正在读的字,但是可以通过 SpeechSynthesisUtterance 的 onboundary 事件来监听每个单词的开始和结束,进而在控制台上输出当前正在读的单词。

具体做法如下:

1. 创建一个 SpeechSynthesisUtterance 对象,设置要朗读的文本。

2. 监听 SpeechSynthesisUtterance 的 onboundary 事件,在事件回调中获取正在读的单词,并将其输出到控制台。

3. 调用 SpeechSynthesisUtterance 的 speak 方法开始朗读。

示例代码:

```
const utterance = new SpeechSynthesisUtterance('Hello World');
utterance.lang = 'en-US';

utterance.addEventListener('boundary', (e) => {
const word = utterance.text.substring(e.charIndex, utterance.text.indexOf(' ', e.charIndex));
console.log(`当前正在读的单词: ${word}`);
});

speechSynthesis.speak(utterance);
```
本页由《梦行文档》生成

 

name完成
30