从一个简单的示例讲起

以下是一个使用了语音合成API的网页:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <input id="input" />
  11. <button onclick="read()">阅读</button>
  12. <script>
  13. function read() {
  14. let input = document.getElementById('input');
  15. let inputValue = input.value;
  16. console.log(inputValue);
  17. let voiceValue = new SpeechSynthesisUtterance(inputValue);
  18. speechSynthesis.speak(voiceValue);
  19. }
  20. </script>
  21. </body>
  22. </html>

在输入框中输入值,点击“阅读”按钮,可以在浏览器中发出阅读输入的值。

参考资料