js文字转语音播放 SpeechSynthesisUtterance

SpeechSynthesisUtterance 是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等 


const speech = new SpeechSynthesisUtterance();
speech.pitch = 1 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)
speech.rate = 1 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)
speech.text = '加油啊';
window.speechSynthesis.speak(speech);

缺点不兼容 IE 浏览器

示例代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="textMsg" value="有新的订单,请及时处理">
  <button onclick="speak()">播放</button>
  <button onclick="pause()">暂停</button>
  <button onclick="resume()">继续播放</button>
  <button onclick="cancel()">取消播放</button>
  <script>
    var speech = new SpeechSynthesisUtterance();
    // 播放
    function speak() {
      // speech.pitch = 1 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)
      // speech.rate  = 5 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)
      // speech.voice = 10 // 获取并设置说话的声音
      // speech.volume = 1 // 获取并设置说话的音量
      // speech.lang = speechSynthesis.getVoices()[0] // 设置播放语言,测试没效果
      // speech.cancel() // 删除队列中所有的语音.如果正在播放,则直接停止
      speech.text = textMsg.value || '这是要说的话' // 获取并设置说话时的文本
      speechSynthesis.speak(speech);
    }
    // 暂停
    function pause() {
      speechSynthesis.pause()
    }
    // 继续播放
    function resume() {
      speechSynthesis.resume()
    }
    // 取消播放
    function cancel() {
      speechSynthesis.cancel()
    }
  </script>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值