Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 JS 朗读文章内容 #40

Open
fantasticit opened this issue Mar 27, 2020 · 0 comments
Open

使用 JS 朗读文章内容 #40

fantasticit opened this issue Mar 27, 2020 · 0 comments
Labels

Comments

@fantasticit
Copy link
Owner

fantasticit commented Mar 27, 2020

今天,从 MDN 上看到了 SpeechSynthesis 这个API。看了下它的介绍。
网页语音 API 的 SpeechSynthesis 接口是语音服务的控制接口;它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令。
卧槽,这一看不得了啊,这个接口可以调用设备接口读出文字,那这样岂不是就可以在web页面上实现朗读功能。来,试一下:

function speak() {
  let synth = window.speechSynthesis;
  let voices = synth.getVoices().filter(voice => voice.lang === 'zh-CN');
  if (voices.length == 0) return;
  let utterThis = new SpeechSynthesisUtterance(document.querySelector('#issue-589242640 > div > div.edit-comment-hide > task-lists > table > tbody > tr > td').textContent);
  utterThis.voice = voices[0];
  synth.speak(utterThis);
}

可在本博客页面打开控制台,并执行代码,体验一下“朗读功能”。(如果没有朗读,可以再调一次 speak()❤️😄😁)

在控制台打印一下 voices

应该是不同的硬件设备,不同的操作系统,可用的 voices 不一样,比如 mac 和 windows。

最后,看一下兼容性还不错。😹💓

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant