基本示例

浏览器 web api 功能,语音读取

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <input type="text" id="textMsg" value="有新的订单,请及时处理">
  10. <button onclick="speak()">播放</button>
  11. <button onclick="pause()">暂停</button>
  12. <button onclick="resume()">继续播放</button>
  13. <button onclick="cancel()">取消播放</button>
  14. <script>
  15. var speech = new SpeechSynthesisUtterance();
  16. // 播放
  17. function speak() {
  18. // speech.pitch = 1 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)
  19. // speech.rate = 5 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)
  20. // speech.voice = 10 // 获取并设置说话的声音
  21. // speech.volume = 1 // 获取并设置说话的音量
  22. // speech.lang = speechSynthesis.getVoices()[0] // 设置播放语言,测试没效果
  23. // speech.cancel() // 删除队列中所有的语音.如果正在播放,则直接停止
  24. speech.text = textMsg.value // 获取并设置说话时的文本
  25. speechSynthesis.speak(speech);
  26. }
  27. // 暂停
  28. function pause() {
  29. speechSynthesis.pause()
  30. }
  31. // 继续播放
  32. function resume() {
  33. speechSynthesis.resume()
  34. }
  35. // 取消播放
  36. function cancel() {
  37. speechSynthesis.cancel()
  38. }
  39. </script>
  40. </body>
  41. </html>

参考

【1】js文字转语音播放-掘金